repo_name
stringclasses
6 values
pr_number
int64
512
78.9k
pr_title
stringlengths
3
144
pr_description
stringlengths
0
30.3k
author
stringlengths
2
21
date_created
unknown
date_merged
unknown
previous_commit
stringlengths
40
40
pr_commit
stringlengths
40
40
query
stringlengths
17
30.4k
filepath
stringlengths
9
210
before_content
stringlengths
0
112M
after_content
stringlengths
0
112M
label
int64
-1
1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/EditorFeatures/CSharpTest/Diagnostics/AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Editor.UnitTests; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics { public abstract partial class AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest : AbstractDiagnosticProviderBasedUserDiagnosticTest { protected AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest(ITestOutputHelper logger) : base(logger) { } protected override ParseOptions GetScriptOptions() => Options.Script; protected internal override string GetLanguage() => LanguageNames.CSharp; protected const string IAsyncEnumerable = @" namespace System { public interface IAsyncDisposable { System.Threading.Tasks.ValueTask DisposeAsync(); } } namespace System.Runtime.CompilerServices { using System.Threading.Tasks; public sealed class AsyncMethodBuilderAttribute : Attribute { public AsyncMethodBuilderAttribute(Type builderType) { } public Type BuilderType { get; } } public struct AsyncValueTaskMethodBuilder { public ValueTask Task => default; public static AsyncValueTaskMethodBuilder Create() => default; public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine {} public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine {} public void SetException(Exception exception) {} public void SetResult() {} public void SetStateMachine(IAsyncStateMachine stateMachine) {} public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine {} } public readonly struct ValueTaskAwaiter : ICriticalNotifyCompletion, INotifyCompletion { public bool IsCompleted => default; public void GetResult() { } public void OnCompleted(Action continuation) { } public void UnsafeOnCompleted(Action continuation) { } } public readonly struct ValueTaskAwaiter<TResult> : ICriticalNotifyCompletion, INotifyCompletion { public bool IsCompleted => default; public TResult GetResult() => default; public void OnCompleted(Action continuation) { } public void UnsafeOnCompleted(Action continuation) { } } } namespace System.Threading.Tasks { using System.Runtime.CompilerServices; [AsyncMethodBuilder(typeof(AsyncValueTaskMethodBuilder))] public readonly struct ValueTask : IEquatable<ValueTask> { public ValueTask(Task task) {} public ValueTask(IValueTaskSource source, short token) {} public bool IsCompleted => default; public bool IsCompletedSuccessfully => default; public bool IsFaulted => default; public bool IsCanceled => default; public Task AsTask() => default; public ConfiguredValueTaskAwaitable ConfigureAwait(bool continueOnCapturedContext) => default; public override bool Equals(object obj) => default; public bool Equals(ValueTask other) => default; public ValueTaskAwaiter GetAwaiter() => default; public override int GetHashCode() => default; public ValueTask Preserve() => default; public static bool operator ==(ValueTask left, ValueTask right) => default; public static bool operator !=(ValueTask left, ValueTask right) => default; } [AsyncMethodBuilder(typeof(AsyncValueTaskMethodBuilder<>))] public readonly struct ValueTask<TResult> : IEquatable<ValueTask<TResult>> { public ValueTask(TResult result) {} public ValueTask(Task<TResult> task) {} public ValueTask(IValueTaskSource<TResult> source, short token) {} public bool IsFaulted => default; public bool IsCompletedSuccessfully => default; public bool IsCompleted => default; public bool IsCanceled => default; public TResult Result => default; public Task<TResult> AsTask() => default; public ConfiguredValueTaskAwaitable<TResult> ConfigureAwait(bool continueOnCapturedContext) => default; public bool Equals(ValueTask<TResult> other) => default; public override bool Equals(object obj) => default; public ValueTaskAwaiter<TResult> GetAwaiter() => default; public override int GetHashCode() => default; public ValueTask<TResult> Preserve() => default; public override string ToString() => default; public static bool operator ==(ValueTask<TResult> left, ValueTask<TResult> right) => default; public static bool operator !=(ValueTask<TResult> left, ValueTask<TResult> right) => default; } } namespace System.Collections.Generic { public interface IAsyncEnumerable<out T> { IAsyncEnumerator<T> GetAsyncEnumerator(); } public interface IAsyncEnumerator<out T> : IAsyncDisposable { System.Threading.Tasks.ValueTask<bool> MoveNextAsync(); T Current { get; } } }"; internal OptionsCollection RequireArithmeticBinaryParenthesesForClarity => ParenthesesOptionsProvider.RequireArithmeticBinaryParenthesesForClarity; internal OptionsCollection RequireRelationalBinaryParenthesesForClarity => ParenthesesOptionsProvider.RequireRelationalBinaryParenthesesForClarity; internal OptionsCollection RequireOtherBinaryParenthesesForClarity => ParenthesesOptionsProvider.RequireOtherBinaryParenthesesForClarity; internal OptionsCollection IgnoreAllParentheses => ParenthesesOptionsProvider.IgnoreAllParentheses; internal OptionsCollection RemoveAllUnnecessaryParentheses => ParenthesesOptionsProvider.RemoveAllUnnecessaryParentheses; internal OptionsCollection RequireAllParenthesesForClarity => ParenthesesOptionsProvider.RequireAllParenthesesForClarity; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Editor.UnitTests; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics { public abstract partial class AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest : AbstractDiagnosticProviderBasedUserDiagnosticTest { protected AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest(ITestOutputHelper logger) : base(logger) { } protected override ParseOptions GetScriptOptions() => Options.Script; protected internal override string GetLanguage() => LanguageNames.CSharp; protected const string IAsyncEnumerable = @" namespace System { public interface IAsyncDisposable { System.Threading.Tasks.ValueTask DisposeAsync(); } } namespace System.Runtime.CompilerServices { using System.Threading.Tasks; public sealed class AsyncMethodBuilderAttribute : Attribute { public AsyncMethodBuilderAttribute(Type builderType) { } public Type BuilderType { get; } } public struct AsyncValueTaskMethodBuilder { public ValueTask Task => default; public static AsyncValueTaskMethodBuilder Create() => default; public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine {} public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine {} public void SetException(Exception exception) {} public void SetResult() {} public void SetStateMachine(IAsyncStateMachine stateMachine) {} public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine {} } public readonly struct ValueTaskAwaiter : ICriticalNotifyCompletion, INotifyCompletion { public bool IsCompleted => default; public void GetResult() { } public void OnCompleted(Action continuation) { } public void UnsafeOnCompleted(Action continuation) { } } public readonly struct ValueTaskAwaiter<TResult> : ICriticalNotifyCompletion, INotifyCompletion { public bool IsCompleted => default; public TResult GetResult() => default; public void OnCompleted(Action continuation) { } public void UnsafeOnCompleted(Action continuation) { } } } namespace System.Threading.Tasks { using System.Runtime.CompilerServices; [AsyncMethodBuilder(typeof(AsyncValueTaskMethodBuilder))] public readonly struct ValueTask : IEquatable<ValueTask> { public ValueTask(Task task) {} public ValueTask(IValueTaskSource source, short token) {} public bool IsCompleted => default; public bool IsCompletedSuccessfully => default; public bool IsFaulted => default; public bool IsCanceled => default; public Task AsTask() => default; public ConfiguredValueTaskAwaitable ConfigureAwait(bool continueOnCapturedContext) => default; public override bool Equals(object obj) => default; public bool Equals(ValueTask other) => default; public ValueTaskAwaiter GetAwaiter() => default; public override int GetHashCode() => default; public ValueTask Preserve() => default; public static bool operator ==(ValueTask left, ValueTask right) => default; public static bool operator !=(ValueTask left, ValueTask right) => default; } [AsyncMethodBuilder(typeof(AsyncValueTaskMethodBuilder<>))] public readonly struct ValueTask<TResult> : IEquatable<ValueTask<TResult>> { public ValueTask(TResult result) {} public ValueTask(Task<TResult> task) {} public ValueTask(IValueTaskSource<TResult> source, short token) {} public bool IsFaulted => default; public bool IsCompletedSuccessfully => default; public bool IsCompleted => default; public bool IsCanceled => default; public TResult Result => default; public Task<TResult> AsTask() => default; public ConfiguredValueTaskAwaitable<TResult> ConfigureAwait(bool continueOnCapturedContext) => default; public bool Equals(ValueTask<TResult> other) => default; public override bool Equals(object obj) => default; public ValueTaskAwaiter<TResult> GetAwaiter() => default; public override int GetHashCode() => default; public ValueTask<TResult> Preserve() => default; public override string ToString() => default; public static bool operator ==(ValueTask<TResult> left, ValueTask<TResult> right) => default; public static bool operator !=(ValueTask<TResult> left, ValueTask<TResult> right) => default; } } namespace System.Collections.Generic { public interface IAsyncEnumerable<out T> { IAsyncEnumerator<T> GetAsyncEnumerator(); } public interface IAsyncEnumerator<out T> : IAsyncDisposable { System.Threading.Tasks.ValueTask<bool> MoveNextAsync(); T Current { get; } } }"; internal OptionsCollection RequireArithmeticBinaryParenthesesForClarity => ParenthesesOptionsProvider.RequireArithmeticBinaryParenthesesForClarity; internal OptionsCollection RequireRelationalBinaryParenthesesForClarity => ParenthesesOptionsProvider.RequireRelationalBinaryParenthesesForClarity; internal OptionsCollection RequireOtherBinaryParenthesesForClarity => ParenthesesOptionsProvider.RequireOtherBinaryParenthesesForClarity; internal OptionsCollection IgnoreAllParentheses => ParenthesesOptionsProvider.IgnoreAllParentheses; internal OptionsCollection RemoveAllUnnecessaryParentheses => ParenthesesOptionsProvider.RemoveAllUnnecessaryParentheses; internal OptionsCollection RequireAllParenthesesForClarity => ParenthesesOptionsProvider.RequireAllParenthesesForClarity; } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/VisualStudio/Core/Impl/RoslynVisualStudioWorkspace.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.ComponentModel.Composition; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.GoToDefinition; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editor.Undo; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio.Composition; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser.Lists; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.Shell; using Roslyn.Utilities; using IAsyncServiceProvider = Microsoft.VisualStudio.Shell.IAsyncServiceProvider; namespace Microsoft.VisualStudio.LanguageServices { [Export(typeof(VisualStudioWorkspace))] [Export(typeof(VisualStudioWorkspaceImpl))] internal class RoslynVisualStudioWorkspace : VisualStudioWorkspaceImpl { private readonly IThreadingContext _threadingContext; /// <remarks> /// Must be lazily constructed since the <see cref="IStreamingFindUsagesPresenter"/> implementation imports a /// backreference to <see cref="VisualStudioWorkspace"/>. /// </remarks> private readonly Lazy<IStreamingFindUsagesPresenter> _streamingPresenter; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public RoslynVisualStudioWorkspace( ExportProvider exportProvider, IThreadingContext threadingContext, Lazy<IStreamingFindUsagesPresenter> streamingPresenter, [Import(typeof(SVsServiceProvider))] IAsyncServiceProvider asyncServiceProvider) : base(exportProvider, asyncServiceProvider) { _threadingContext = threadingContext; _streamingPresenter = streamingPresenter; } internal override IInvisibleEditor OpenInvisibleEditor(DocumentId documentId) { var globalUndoService = this.Services.GetRequiredService<IGlobalUndoService>(); var needsUndoDisabled = false; var textDocument = this.CurrentSolution.GetTextDocument(documentId); if (textDocument == null) { throw new InvalidOperationException(string.Format(WorkspacesResources._0_is_not_part_of_the_workspace, documentId)); } // Do not save the file if is open and there is not a global undo transaction. var needsSave = globalUndoService.IsGlobalTransactionOpen(this) || !this.IsDocumentOpen(documentId); if (needsSave) { if (textDocument is Document document) { // Disable undo on generated documents needsUndoDisabled = document.IsGeneratedCode(CancellationToken.None); } else { // Enable undo on "additional documents" or if no document can be found. needsUndoDisabled = false; } } // Documents in the VisualStudioWorkspace always have file paths since that's how we get files given // to us from the project system. Contract.ThrowIfNull(textDocument.FilePath); return new InvisibleEditor(ServiceProvider.GlobalProvider, textDocument.FilePath, GetHierarchy(documentId.ProjectId), needsSave, needsUndoDisabled); } [Obsolete("Use TryGoToDefinitionAsync instead", error: true)] public override bool TryGoToDefinition(ISymbol symbol, Project project, CancellationToken cancellationToken) => _threadingContext.JoinableTaskFactory.Run(() => TryGoToDefinitionAsync(symbol, project, cancellationToken)); public override async Task<bool> TryGoToDefinitionAsync( ISymbol symbol, Project project, CancellationToken cancellationToken) { var currentProject = project.Solution.Workspace.CurrentSolution.GetProject(project.Id); if (currentProject == null) return false; var symbolId = SymbolKey.Create(symbol, cancellationToken); var currentCompilation = await currentProject.GetRequiredCompilationAsync(cancellationToken).ConfigureAwait(false); var symbolInfo = symbolId.Resolve(currentCompilation, cancellationToken: cancellationToken); if (symbolInfo.Symbol == null) return false; return await GoToDefinitionHelpers.TryGoToDefinitionAsync( symbolInfo.Symbol, currentProject.Solution, _threadingContext, _streamingPresenter.Value, cancellationToken).ConfigureAwait(false); } public override bool TryFindAllReferences(ISymbol symbol, Project project, CancellationToken cancellationToken) { // Legacy API. Previously used by ObjectBrowser to support 'FindRefs' off of an // object browser item. Now ObjectBrowser goes through the streaming-FindRefs system. return false; } public override void DisplayReferencedSymbols(Solution solution, IEnumerable<ReferencedSymbol> referencedSymbols) { // Legacy API. Previously used by ObjectBrowser to support 'FindRefs' off of an // object browser item. Now ObjectBrowser goes through the streaming-FindRefs system. } internal override object? GetBrowseObject(SymbolListItem symbolListItem) { var compilation = symbolListItem.GetCompilation(this); if (compilation == null) { return null; } var symbol = symbolListItem.ResolveSymbol(compilation); var sourceLocation = symbol.Locations.Where(l => l.IsInSource).FirstOrDefault(); if (sourceLocation == null) { return null; } var projectId = symbolListItem.ProjectId; if (projectId == null) { return null; } var project = this.CurrentSolution.GetProject(projectId); if (project == null) { return null; } var codeModelService = project.LanguageServices.GetService<ICodeModelService>(); if (codeModelService == null) { return null; } var tree = sourceLocation.SourceTree; Contract.ThrowIfNull(tree, "We have a location that was in source, but doesn't have a SourceTree."); var document = project.GetDocument(tree); Contract.ThrowIfNull(document, "We have a symbol coming from a tree, and that tree isn't in the Project it supposedly came from."); var vsFileCodeModel = this.GetFileCodeModel(document.Id); var fileCodeModel = ComAggregate.GetManagedObject<FileCodeModel>(vsFileCodeModel); if (fileCodeModel != null) { var syntaxNode = tree.GetRoot().FindNode(sourceLocation.SourceSpan); while (syntaxNode != null) { if (!codeModelService.TryGetNodeKey(syntaxNode).IsEmpty) { break; } syntaxNode = syntaxNode.Parent; } if (syntaxNode != null) { var codeElement = fileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(syntaxNode); if (codeElement != null) { return codeElement; } } } return null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.GoToDefinition; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editor.Undo; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio.Composition; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser.Lists; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.Shell; using Roslyn.Utilities; using IAsyncServiceProvider = Microsoft.VisualStudio.Shell.IAsyncServiceProvider; namespace Microsoft.VisualStudio.LanguageServices { [Export(typeof(VisualStudioWorkspace))] [Export(typeof(VisualStudioWorkspaceImpl))] internal class RoslynVisualStudioWorkspace : VisualStudioWorkspaceImpl { private readonly IThreadingContext _threadingContext; /// <remarks> /// Must be lazily constructed since the <see cref="IStreamingFindUsagesPresenter"/> implementation imports a /// backreference to <see cref="VisualStudioWorkspace"/>. /// </remarks> private readonly Lazy<IStreamingFindUsagesPresenter> _streamingPresenter; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public RoslynVisualStudioWorkspace( ExportProvider exportProvider, IThreadingContext threadingContext, Lazy<IStreamingFindUsagesPresenter> streamingPresenter, [Import(typeof(SVsServiceProvider))] IAsyncServiceProvider asyncServiceProvider) : base(exportProvider, asyncServiceProvider) { _threadingContext = threadingContext; _streamingPresenter = streamingPresenter; } internal override IInvisibleEditor OpenInvisibleEditor(DocumentId documentId) { var globalUndoService = this.Services.GetRequiredService<IGlobalUndoService>(); var needsUndoDisabled = false; var textDocument = this.CurrentSolution.GetTextDocument(documentId); if (textDocument == null) { throw new InvalidOperationException(string.Format(WorkspacesResources._0_is_not_part_of_the_workspace, documentId)); } // Do not save the file if is open and there is not a global undo transaction. var needsSave = globalUndoService.IsGlobalTransactionOpen(this) || !this.IsDocumentOpen(documentId); if (needsSave) { if (textDocument is Document document) { // Disable undo on generated documents needsUndoDisabled = document.IsGeneratedCode(CancellationToken.None); } else { // Enable undo on "additional documents" or if no document can be found. needsUndoDisabled = false; } } // Documents in the VisualStudioWorkspace always have file paths since that's how we get files given // to us from the project system. Contract.ThrowIfNull(textDocument.FilePath); return new InvisibleEditor(ServiceProvider.GlobalProvider, textDocument.FilePath, GetHierarchy(documentId.ProjectId), needsSave, needsUndoDisabled); } [Obsolete("Use TryGoToDefinitionAsync instead", error: true)] public override bool TryGoToDefinition(ISymbol symbol, Project project, CancellationToken cancellationToken) => _threadingContext.JoinableTaskFactory.Run(() => TryGoToDefinitionAsync(symbol, project, cancellationToken)); public override async Task<bool> TryGoToDefinitionAsync( ISymbol symbol, Project project, CancellationToken cancellationToken) { var currentProject = project.Solution.Workspace.CurrentSolution.GetProject(project.Id); if (currentProject == null) return false; var symbolId = SymbolKey.Create(symbol, cancellationToken); var currentCompilation = await currentProject.GetRequiredCompilationAsync(cancellationToken).ConfigureAwait(false); var symbolInfo = symbolId.Resolve(currentCompilation, cancellationToken: cancellationToken); if (symbolInfo.Symbol == null) return false; return await GoToDefinitionHelpers.TryGoToDefinitionAsync( symbolInfo.Symbol, currentProject.Solution, _threadingContext, _streamingPresenter.Value, cancellationToken).ConfigureAwait(false); } public override bool TryFindAllReferences(ISymbol symbol, Project project, CancellationToken cancellationToken) { // Legacy API. Previously used by ObjectBrowser to support 'FindRefs' off of an // object browser item. Now ObjectBrowser goes through the streaming-FindRefs system. return false; } public override void DisplayReferencedSymbols(Solution solution, IEnumerable<ReferencedSymbol> referencedSymbols) { // Legacy API. Previously used by ObjectBrowser to support 'FindRefs' off of an // object browser item. Now ObjectBrowser goes through the streaming-FindRefs system. } internal override object? GetBrowseObject(SymbolListItem symbolListItem) { var compilation = symbolListItem.GetCompilation(this); if (compilation == null) { return null; } var symbol = symbolListItem.ResolveSymbol(compilation); var sourceLocation = symbol.Locations.Where(l => l.IsInSource).FirstOrDefault(); if (sourceLocation == null) { return null; } var projectId = symbolListItem.ProjectId; if (projectId == null) { return null; } var project = this.CurrentSolution.GetProject(projectId); if (project == null) { return null; } var codeModelService = project.LanguageServices.GetService<ICodeModelService>(); if (codeModelService == null) { return null; } var tree = sourceLocation.SourceTree; Contract.ThrowIfNull(tree, "We have a location that was in source, but doesn't have a SourceTree."); var document = project.GetDocument(tree); Contract.ThrowIfNull(document, "We have a symbol coming from a tree, and that tree isn't in the Project it supposedly came from."); var vsFileCodeModel = this.GetFileCodeModel(document.Id); var fileCodeModel = ComAggregate.GetManagedObject<FileCodeModel>(vsFileCodeModel); if (fileCodeModel != null) { var syntaxNode = tree.GetRoot().FindNode(sourceLocation.SourceSpan); while (syntaxNode != null) { if (!codeModelService.TryGetNodeKey(syntaxNode).IsEmpty) { break; } syntaxNode = syntaxNode.Parent; } if (syntaxNode != null) { var codeElement = fileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(syntaxNode); if (codeElement != null) { return codeElement; } } } return null; } } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/Features/Core/Portable/ExternalAccess/VSTypeScript/Api/VSTypeScriptDocumentNavigationServiceWrapper.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Navigation; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api { internal readonly struct VSTypeScriptDocumentNavigationServiceWrapper { private readonly IDocumentNavigationService _underlyingObject; public VSTypeScriptDocumentNavigationServiceWrapper(IDocumentNavigationService underlyingObject) => _underlyingObject = underlyingObject; public static VSTypeScriptDocumentNavigationServiceWrapper Create(Workspace workspace) => new(workspace.Services.GetRequiredService<IDocumentNavigationService>()); [Obsolete("Call overload that takes a CancellationToken", error: false)] public bool TryNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace = 0, OptionSet? options = null) => this.TryNavigateToPosition(workspace, documentId, position, virtualSpace, options, CancellationToken.None); /// <inheritdoc cref="IDocumentNavigationService.TryNavigateToPosition"/> public bool TryNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace, OptionSet? options, CancellationToken cancellationToken) => _underlyingObject.TryNavigateToPosition(workspace, documentId, position, virtualSpace, options, cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api { internal readonly struct VSTypeScriptDocumentNavigationServiceWrapper { private readonly IDocumentNavigationService _underlyingObject; public VSTypeScriptDocumentNavigationServiceWrapper(IDocumentNavigationService underlyingObject) => _underlyingObject = underlyingObject; public static VSTypeScriptDocumentNavigationServiceWrapper Create(Workspace workspace) => new(workspace.Services.GetRequiredService<IDocumentNavigationService>()); [Obsolete("Call overload that takes a CancellationToken", error: false)] public bool TryNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace = 0, OptionSet? options = null) => this.TryNavigateToPosition(workspace, documentId, position, virtualSpace, options, CancellationToken.None); /// <inheritdoc cref="IDocumentNavigationService.TryNavigateToPosition"/> public bool TryNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace, OptionSet? options, CancellationToken cancellationToken) => _underlyingObject.TryNavigateToPosition(workspace, documentId, position, virtualSpace, options, cancellationToken); } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/Compilers/Core/CodeAnalysisTest/CommonParseOptionsTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { public class CommonParseOptionsTests { /// <summary> /// If this test fails, please update the <see cref="ParseOptions.GetHashCodeHelper"/> /// and <see cref="ParseOptions.EqualsHelper"/> methods to /// make sure they are doing the right thing with your new field and then update the baseline /// here. /// </summary> [Fact] public void TestFieldsForEqualsAndGetHashCode() { ReflectionAssert.AssertPublicAndInternalFieldsAndProperties( typeof(ParseOptions), "DocumentationMode", "Errors", "Features", "Kind", "Language", "PreprocessorSymbolNames", "SpecifiedKind"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { public class CommonParseOptionsTests { /// <summary> /// If this test fails, please update the <see cref="ParseOptions.GetHashCodeHelper"/> /// and <see cref="ParseOptions.EqualsHelper"/> methods to /// make sure they are doing the right thing with your new field and then update the baseline /// here. /// </summary> [Fact] public void TestFieldsForEqualsAndGetHashCode() { ReflectionAssert.AssertPublicAndInternalFieldsAndProperties( typeof(ParseOptions), "DocumentationMode", "Errors", "Features", "Kind", "Language", "PreprocessorSymbolNames", "SpecifiedKind"); } } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/Workspaces/Core/Portable/CodeGeneration/Symbols/CodeGenerationPointerTypeSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; namespace Microsoft.CodeAnalysis.CodeGeneration { internal class CodeGenerationPointerTypeSymbol : CodeGenerationTypeSymbol, IPointerTypeSymbol { public ITypeSymbol PointedAtType { get; } public CodeGenerationPointerTypeSymbol(ITypeSymbol pointedAtType) : base(null, null, default, Accessibility.NotApplicable, default, string.Empty, SpecialType.None, NullableAnnotation.None) { this.PointedAtType = pointedAtType; } protected override CodeGenerationTypeSymbol CloneWithNullableAnnotation(NullableAnnotation nullableAnnotation) { // We ignore the nullableAnnotation parameter because pointer types can't be nullable. return new CodeGenerationPointerTypeSymbol(this.PointedAtType); } public override TypeKind TypeKind => TypeKind.Pointer; public override SymbolKind Kind => SymbolKind.PointerType; public override void Accept(SymbolVisitor visitor) => visitor.VisitPointerType(this); public override TResult Accept<TResult>(SymbolVisitor<TResult> visitor) => visitor.VisitPointerType(this); public ImmutableArray<CustomModifier> CustomModifiers { get { return ImmutableArray.Create<CustomModifier>(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; namespace Microsoft.CodeAnalysis.CodeGeneration { internal class CodeGenerationPointerTypeSymbol : CodeGenerationTypeSymbol, IPointerTypeSymbol { public ITypeSymbol PointedAtType { get; } public CodeGenerationPointerTypeSymbol(ITypeSymbol pointedAtType) : base(null, null, default, Accessibility.NotApplicable, default, string.Empty, SpecialType.None, NullableAnnotation.None) { this.PointedAtType = pointedAtType; } protected override CodeGenerationTypeSymbol CloneWithNullableAnnotation(NullableAnnotation nullableAnnotation) { // We ignore the nullableAnnotation parameter because pointer types can't be nullable. return new CodeGenerationPointerTypeSymbol(this.PointedAtType); } public override TypeKind TypeKind => TypeKind.Pointer; public override SymbolKind Kind => SymbolKind.PointerType; public override void Accept(SymbolVisitor visitor) => visitor.VisitPointerType(this); public override TResult Accept<TResult>(SymbolVisitor<TResult> visitor) => visitor.VisitPointerType(this); public ImmutableArray<CustomModifier> CustomModifiers { get { return ImmutableArray.Create<CustomModifier>(); } } } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/Compilers/CSharp/Portable/Symbols/Source/SourceTypeParameterSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Base class for type and method type parameters. /// </summary> internal abstract class SourceTypeParameterSymbolBase : TypeParameterSymbol, IAttributeTargetSymbol { private readonly ImmutableArray<SyntaxReference> _syntaxRefs; private readonly ImmutableArray<Location> _locations; private readonly string _name; private readonly short _ordinal; private SymbolCompletionState _state; private CustomAttributesBag<CSharpAttributeData> _lazyCustomAttributesBag; private TypeParameterBounds _lazyBounds = TypeParameterBounds.Unset; protected SourceTypeParameterSymbolBase(string name, int ordinal, ImmutableArray<Location> locations, ImmutableArray<SyntaxReference> syntaxRefs) { Debug.Assert(!syntaxRefs.IsEmpty); _name = name; _ordinal = (short)ordinal; _locations = locations; _syntaxRefs = syntaxRefs; } public override ImmutableArray<Location> Locations { get { return _locations; } } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { return _syntaxRefs; } } internal ImmutableArray<SyntaxReference> SyntaxReferences { get { return _syntaxRefs; } } public override int Ordinal { get { return _ordinal; } } public override VarianceKind Variance { get { return VarianceKind.None; } } public override string Name { get { return _name; } } internal override ImmutableArray<TypeWithAnnotations> GetConstraintTypes(ConsList<TypeParameterSymbol> inProgress) { var bounds = this.GetBounds(inProgress); return (bounds != null) ? bounds.ConstraintTypes : ImmutableArray<TypeWithAnnotations>.Empty; } internal override ImmutableArray<NamedTypeSymbol> GetInterfaces(ConsList<TypeParameterSymbol> inProgress) { var bounds = this.GetBounds(inProgress); return (bounds != null) ? bounds.Interfaces : ImmutableArray<NamedTypeSymbol>.Empty; } internal override NamedTypeSymbol GetEffectiveBaseClass(ConsList<TypeParameterSymbol> inProgress) { var bounds = this.GetBounds(inProgress); return (bounds != null) ? bounds.EffectiveBaseClass : this.GetDefaultBaseType(); } internal override TypeSymbol GetDeducedBaseType(ConsList<TypeParameterSymbol> inProgress) { var bounds = this.GetBounds(inProgress); return (bounds != null) ? bounds.DeducedBaseType : this.GetDefaultBaseType(); } internal ImmutableArray<SyntaxList<AttributeListSyntax>> MergedAttributeDeclarationSyntaxLists { get { var mergedAttributesBuilder = ArrayBuilder<SyntaxList<AttributeListSyntax>>.GetInstance(); foreach (var syntaxRef in _syntaxRefs) { var syntax = (TypeParameterSyntax)syntaxRef.GetSyntax(); mergedAttributesBuilder.Add(syntax.AttributeLists); } var sourceMethod = this.ContainingSymbol as SourceOrdinaryMethodSymbol; if ((object)sourceMethod != null && sourceMethod.IsPartial) { var implementingPart = sourceMethod.SourcePartialImplementation; if ((object)implementingPart != null) { var typeParameter = (SourceTypeParameterSymbolBase)implementingPart.TypeParameters[_ordinal]; mergedAttributesBuilder.AddRange(typeParameter.MergedAttributeDeclarationSyntaxLists); } } return mergedAttributesBuilder.ToImmutableAndFree(); } } IAttributeTargetSymbol IAttributeTargetSymbol.AttributesOwner { get { return this; } } AttributeLocation IAttributeTargetSymbol.DefaultAttributeLocation { get { return AttributeLocation.TypeParameter; } } AttributeLocation IAttributeTargetSymbol.AllowedAttributeLocations { get { return AttributeLocation.TypeParameter; } } /// <summary> /// Gets the attributes applied on this symbol. /// Returns an empty array if there are no attributes. /// </summary> /// <remarks> /// NOTE: This method should always be kept as a sealed override. /// If you want to override attribute binding logic for a sub-class, then override <see cref="GetAttributesBag"/> method. /// </remarks> public sealed override ImmutableArray<CSharpAttributeData> GetAttributes() { return this.GetAttributesBag().Attributes; } /// <summary> /// Returns a bag of applied custom attributes and data decoded from well-known attributes. Returns null if there are no attributes applied on the symbol. /// </summary> /// <remarks> /// Forces binding and decoding of attributes. /// </remarks> internal virtual CustomAttributesBag<CSharpAttributeData> GetAttributesBag() { if (_lazyCustomAttributesBag == null || !_lazyCustomAttributesBag.IsSealed) { bool lazyAttributesStored = false; var sourceMethod = this.ContainingSymbol as SourceOrdinaryMethodSymbol; if ((object)sourceMethod == null || (object)sourceMethod.SourcePartialDefinition == null) { lazyAttributesStored = LoadAndValidateAttributes( OneOrMany.Create(this.MergedAttributeDeclarationSyntaxLists), ref _lazyCustomAttributesBag, binderOpt: (ContainingSymbol as LocalFunctionSymbol)?.SignatureBinder); } else { var typeParameter = (SourceTypeParameterSymbolBase)sourceMethod.SourcePartialDefinition.TypeParameters[_ordinal]; CustomAttributesBag<CSharpAttributeData> attributesBag = typeParameter.GetAttributesBag(); lazyAttributesStored = Interlocked.CompareExchange(ref _lazyCustomAttributesBag, attributesBag, null) == null; } if (lazyAttributesStored) { _state.NotePartComplete(CompletionPart.Attributes); } } return _lazyCustomAttributesBag; } internal override void EnsureAllConstraintsAreResolved() { if (!_lazyBounds.IsSet()) { EnsureAllConstraintsAreResolved(this.ContainerTypeParameters); } } protected abstract ImmutableArray<TypeParameterSymbol> ContainerTypeParameters { get; } private TypeParameterBounds GetBounds(ConsList<TypeParameterSymbol> inProgress) { Debug.Assert(!inProgress.ContainsReference(this)); Debug.Assert(!inProgress.Any() || ReferenceEquals(inProgress.Head.ContainingSymbol, this.ContainingSymbol)); if (!_lazyBounds.IsSet()) { var diagnostics = BindingDiagnosticBag.GetInstance(); var bounds = this.ResolveBounds(inProgress, diagnostics); if (ReferenceEquals(Interlocked.CompareExchange(ref _lazyBounds, bounds, TypeParameterBounds.Unset), TypeParameterBounds.Unset)) { this.CheckConstraintTypeConstraints(diagnostics); this.CheckUnmanagedConstraint(diagnostics); this.EnsureAttributesFromConstraints(diagnostics); this.AddDeclarationDiagnostics(diagnostics); _state.NotePartComplete(CompletionPart.TypeParameterConstraints); } diagnostics.Free(); } return _lazyBounds; } protected abstract TypeParameterBounds ResolveBounds(ConsList<TypeParameterSymbol> inProgress, BindingDiagnosticBag diagnostics); /// <summary> /// Check constraints of generic types referenced in constraint types. For instance, /// with "interface I&lt;T&gt; where T : I&lt;T&gt; {}", check T satisfies constraints /// on I&lt;T&gt;. Those constraints are not checked when binding ConstraintTypes /// since ConstraintTypes has not been set on I&lt;T&gt; at that point. /// </summary> private void CheckConstraintTypeConstraints(BindingDiagnosticBag diagnostics) { var constraintTypes = this.ConstraintTypesNoUseSiteDiagnostics; if (constraintTypes.Length == 0) { return; } var args = new ConstraintsHelper.CheckConstraintsArgsBoxed(DeclaringCompilation, new TypeConversions(ContainingAssembly.CorLibrary), _locations[0], diagnostics); foreach (var constraintType in constraintTypes) { if (!diagnostics.ReportUseSite(constraintType.Type, args.Args.Location)) { constraintType.Type.CheckAllConstraints(args); } } } private void CheckUnmanagedConstraint(BindingDiagnosticBag diagnostics) { if (this.HasUnmanagedTypeConstraint) { DeclaringCompilation.EnsureIsUnmanagedAttributeExists(diagnostics, this.GetNonNullSyntaxNode().Location, ModifyCompilationForAttributeEmbedding()); } } private bool ModifyCompilationForAttributeEmbedding() { bool modifyCompilation; switch (this.ContainingSymbol) { case SourceOrdinaryMethodSymbol _: case SourceMemberContainerTypeSymbol _: modifyCompilation = true; break; case LocalFunctionSymbol _: modifyCompilation = false; break; default: throw ExceptionUtilities.UnexpectedValue(this.ContainingSymbol); } return modifyCompilation; } private void EnsureAttributesFromConstraints(BindingDiagnosticBag diagnostics) { if (ConstraintTypesNoUseSiteDiagnostics.Any(t => t.ContainsNativeInteger())) { DeclaringCompilation.EnsureNativeIntegerAttributeExists(diagnostics, getLocation(), ModifyCompilationForAttributeEmbedding()); } if (ConstraintsNeedNullableAttribute()) { DeclaringCompilation.EnsureNullableAttributeExists(diagnostics, getLocation(), ModifyCompilationForAttributeEmbedding()); } Location getLocation() => this.GetNonNullSyntaxNode().Location; } // See https://github.com/dotnet/roslyn/blob/main/docs/features/nullable-metadata.md internal bool ConstraintsNeedNullableAttribute() { if (!DeclaringCompilation.ShouldEmitNullableAttributes(this)) { return false; } if (this.HasReferenceTypeConstraint && this.ReferenceTypeConstraintIsNullable != null) { return true; } if (this.ConstraintTypesNoUseSiteDiagnostics.Any(c => c.NeedsNullableAttribute())) { return true; } if (this.HasNotNullConstraint) { return true; } return !this.HasReferenceTypeConstraint && !this.HasValueTypeConstraint && this.ConstraintTypesNoUseSiteDiagnostics.IsEmpty && this.IsNotNullable == false; } private NamedTypeSymbol GetDefaultBaseType() { return this.ContainingAssembly.GetSpecialType(SpecialType.System_Object); } internal override void ForceComplete(SourceLocation locationOpt, CancellationToken cancellationToken) { while (true) { cancellationToken.ThrowIfCancellationRequested(); var incompletePart = _state.NextIncompletePart; switch (incompletePart) { case CompletionPart.Attributes: GetAttributes(); break; case CompletionPart.TypeParameterConstraints: var constraintTypes = this.ConstraintTypesNoUseSiteDiagnostics; // Nested type parameter references might not be valid in error scenarios. //Debug.Assert(this.ContainingSymbol.IsContainingSymbolOfAllTypeParameters(this.ConstraintTypes)); //Debug.Assert(this.ContainingSymbol.IsContainingSymbolOfAllTypeParameters(ImmutableArray<TypeSymbol>.CreateFrom(this.Interfaces))); Debug.Assert(this.ContainingSymbol.IsContainingSymbolOfAllTypeParameters(this.EffectiveBaseClassNoUseSiteDiagnostics)); Debug.Assert(this.ContainingSymbol.IsContainingSymbolOfAllTypeParameters(this.DeducedBaseTypeNoUseSiteDiagnostics)); break; case CompletionPart.None: return; default: // any other values are completion parts intended for other kinds of symbols _state.NotePartComplete(CompletionPart.All & ~CompletionPart.TypeParameterSymbolAll); break; } _state.SpinWaitComplete(incompletePart, cancellationToken); } } internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedAttributes(moduleBuilder, ref attributes); if (this.HasUnmanagedTypeConstraint) { AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeIsUnmanagedAttribute(this)); } var compilation = DeclaringCompilation; if (compilation.ShouldEmitNullableAttributes(this)) { AddSynthesizedAttribute( ref attributes, moduleBuilder.SynthesizeNullableAttributeIfNecessary(GetNullableContextValue(), GetSynthesizedNullableAttributeValue())); } } internal byte GetSynthesizedNullableAttributeValue() { if (this.HasReferenceTypeConstraint) { switch (this.ReferenceTypeConstraintIsNullable) { case true: return NullableAnnotationExtensions.AnnotatedAttributeValue; case false: return NullableAnnotationExtensions.NotAnnotatedAttributeValue; } } else if (this.HasNotNullConstraint) { return NullableAnnotationExtensions.NotAnnotatedAttributeValue; } else if (!this.HasValueTypeConstraint && this.ConstraintTypesNoUseSiteDiagnostics.IsEmpty && this.IsNotNullable == false) { return NullableAnnotationExtensions.AnnotatedAttributeValue; } return NullableAnnotationExtensions.ObliviousAttributeValue; } internal sealed override void DecodeWellKnownAttribute(ref DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments) { Debug.Assert((object)arguments.AttributeSyntaxOpt != null); Debug.Assert(arguments.Diagnostics is BindingDiagnosticBag); var attribute = arguments.Attribute; Debug.Assert(!attribute.HasErrors); Debug.Assert(arguments.SymbolPart == AttributeLocation.None); if (attribute.IsTargetAttribute(this, AttributeDescription.NullableAttribute)) { // NullableAttribute should not be set explicitly. ((BindingDiagnosticBag)arguments.Diagnostics).Add(ErrorCode.ERR_ExplicitNullableAttribute, arguments.AttributeSyntaxOpt.Location); } base.DecodeWellKnownAttribute(ref arguments); } protected bool? CalculateReferenceTypeConstraintIsNullable(TypeParameterConstraintKind constraints) { if ((constraints & TypeParameterConstraintKind.ReferenceType) == 0) { return false; } switch (constraints & TypeParameterConstraintKind.AllReferenceTypeKinds) { case TypeParameterConstraintKind.NullableReferenceType: return true; case TypeParameterConstraintKind.NotNullableReferenceType: return false; } return null; } } internal sealed class SourceTypeParameterSymbol : SourceTypeParameterSymbolBase { private readonly SourceNamedTypeSymbol _owner; private readonly VarianceKind _varianceKind; public SourceTypeParameterSymbol(SourceNamedTypeSymbol owner, string name, int ordinal, VarianceKind varianceKind, ImmutableArray<Location> locations, ImmutableArray<SyntaxReference> syntaxRefs) : base(name, ordinal, locations, syntaxRefs) { _owner = owner; _varianceKind = varianceKind; } public override TypeParameterKind TypeParameterKind { get { return TypeParameterKind.Type; } } public override Symbol ContainingSymbol { get { return _owner; } } public override VarianceKind Variance { get { return _varianceKind; } } public override bool HasConstructorConstraint { get { var constraints = this.GetConstraintKinds(); return (constraints & TypeParameterConstraintKind.Constructor) != 0; } } public override bool HasValueTypeConstraint { get { var constraints = this.GetConstraintKinds(); return (constraints & TypeParameterConstraintKind.AllValueTypeKinds) != 0; } } public override bool IsValueTypeFromConstraintTypes { get { Debug.Assert(!HasValueTypeConstraint); var constraints = this.GetConstraintKinds(); return (constraints & TypeParameterConstraintKind.ValueTypeFromConstraintTypes) != 0; } } public override bool HasReferenceTypeConstraint { get { var constraints = this.GetConstraintKinds(); return (constraints & TypeParameterConstraintKind.ReferenceType) != 0; } } public override bool IsReferenceTypeFromConstraintTypes { get { var constraints = this.GetConstraintKinds(); return (constraints & TypeParameterConstraintKind.ReferenceTypeFromConstraintTypes) != 0; } } internal override bool? ReferenceTypeConstraintIsNullable { get { return CalculateReferenceTypeConstraintIsNullable(this.GetConstraintKinds()); } } public override bool HasNotNullConstraint { get { var constraints = this.GetConstraintKinds(); return (constraints & TypeParameterConstraintKind.NotNull) != 0; } } internal override bool? IsNotNullable { get { if ((this.GetConstraintKinds() & TypeParameterConstraintKind.ObliviousNullabilityIfReferenceType) != 0) { return null; } return CalculateIsNotNullable(); } } public override bool HasUnmanagedTypeConstraint { get { var constraints = this.GetConstraintKinds(); return (constraints & TypeParameterConstraintKind.Unmanaged) != 0; } } protected override ImmutableArray<TypeParameterSymbol> ContainerTypeParameters { get { return _owner.TypeParameters; } } protected override TypeParameterBounds ResolveBounds(ConsList<TypeParameterSymbol> inProgress, BindingDiagnosticBag diagnostics) { var constraintTypes = _owner.GetTypeParameterConstraintTypes(this.Ordinal); if (constraintTypes.IsEmpty && GetConstraintKinds() == TypeParameterConstraintKind.None) { return null; } return this.ResolveBounds(this.ContainingAssembly.CorLibrary, inProgress.Prepend(this), constraintTypes, inherited: false, this.DeclaringCompilation, diagnostics); } private TypeParameterConstraintKind GetConstraintKinds() { return _owner.GetTypeParameterConstraintKind(this.Ordinal); } } internal sealed class SourceMethodTypeParameterSymbol : SourceTypeParameterSymbolBase { private readonly SourceMethodSymbol _owner; public SourceMethodTypeParameterSymbol(SourceMethodSymbol owner, string name, int ordinal, ImmutableArray<Location> locations, ImmutableArray<SyntaxReference> syntaxRefs) : base(name, ordinal, locations, syntaxRefs) { _owner = owner; } internal override void AddDeclarationDiagnostics(BindingDiagnosticBag diagnostics) => _owner.AddDeclarationDiagnostics(diagnostics); public override TypeParameterKind TypeParameterKind { get { return TypeParameterKind.Method; } } public override Symbol ContainingSymbol { get { return _owner; } } public override bool HasConstructorConstraint { get { var constraints = this.GetConstraintKinds(); return (constraints & TypeParameterConstraintKind.Constructor) != 0; } } public override bool HasValueTypeConstraint { get { var constraints = this.GetConstraintKinds(); return (constraints & TypeParameterConstraintKind.AllValueTypeKinds) != 0; } } public override bool IsValueTypeFromConstraintTypes { get { Debug.Assert(!HasValueTypeConstraint); var constraints = this.GetConstraintKinds(); return (constraints & TypeParameterConstraintKind.ValueTypeFromConstraintTypes) != 0; } } public override bool HasReferenceTypeConstraint { get { var constraints = this.GetConstraintKinds(); return (constraints & TypeParameterConstraintKind.ReferenceType) != 0; } } public override bool IsReferenceTypeFromConstraintTypes { get { var constraints = this.GetConstraintKinds(); return (constraints & TypeParameterConstraintKind.ReferenceTypeFromConstraintTypes) != 0; } } public override bool HasNotNullConstraint { get { var constraints = this.GetConstraintKinds(); return (constraints & TypeParameterConstraintKind.NotNull) != 0; } } internal override bool? ReferenceTypeConstraintIsNullable { get { return CalculateReferenceTypeConstraintIsNullable(this.GetConstraintKinds()); } } internal override bool? IsNotNullable { get { if ((this.GetConstraintKinds() & TypeParameterConstraintKind.ObliviousNullabilityIfReferenceType) != 0) { return null; } return CalculateIsNotNullable(); } } public override bool HasUnmanagedTypeConstraint { get { var constraints = this.GetConstraintKinds(); return (constraints & TypeParameterConstraintKind.Unmanaged) != 0; } } protected override ImmutableArray<TypeParameterSymbol> ContainerTypeParameters { get { return _owner.TypeParameters; } } protected override TypeParameterBounds ResolveBounds(ConsList<TypeParameterSymbol> inProgress, BindingDiagnosticBag diagnostics) { var constraints = _owner.GetTypeParameterConstraintTypes(); var constraintTypes = constraints.IsEmpty ? ImmutableArray<TypeWithAnnotations>.Empty : constraints[Ordinal]; if (constraintTypes.IsEmpty && GetConstraintKinds() == TypeParameterConstraintKind.None) { return null; } return this.ResolveBounds(this.ContainingAssembly.CorLibrary, inProgress.Prepend(this), constraintTypes, inherited: false, this.DeclaringCompilation, diagnostics); } private TypeParameterConstraintKind GetConstraintKinds() { var constraintKinds = _owner.GetTypeParameterConstraintKinds(); return constraintKinds.IsEmpty ? TypeParameterConstraintKind.None : constraintKinds[Ordinal]; } } /// <summary> /// A map shared by all type parameters for an overriding method or a method /// that explicitly implements an interface. The map caches the overridden method /// and a type map from overridden type parameters to overriding type parameters. /// </summary> internal abstract class OverriddenMethodTypeParameterMapBase { // Method representing overriding or explicit implementation. private readonly SourceOrdinaryMethodSymbol _overridingMethod; // Type map shared by all type parameters for this explicit implementation. private TypeMap _lazyTypeMap; // Overridden or explicitly implemented method. May be null in error cases. private MethodSymbol _lazyOverriddenMethod = ErrorMethodSymbol.UnknownMethod; protected OverriddenMethodTypeParameterMapBase(SourceOrdinaryMethodSymbol overridingMethod) { _overridingMethod = overridingMethod; } public SourceOrdinaryMethodSymbol OverridingMethod { get { return _overridingMethod; } } public TypeParameterSymbol GetOverriddenTypeParameter(int ordinal) { var overriddenMethod = this.OverriddenMethod; return ((object)overriddenMethod != null) ? overriddenMethod.TypeParameters[ordinal] : null; } public TypeMap TypeMap { get { if (_lazyTypeMap == null) { var overriddenMethod = this.OverriddenMethod; if ((object)overriddenMethod != null) { var overriddenTypeParameters = overriddenMethod.TypeParameters; var overridingTypeParameters = _overridingMethod.TypeParameters; Debug.Assert(overriddenTypeParameters.Length == overridingTypeParameters.Length); var typeMap = new TypeMap(overriddenTypeParameters, overridingTypeParameters, allowAlpha: true); Interlocked.CompareExchange(ref _lazyTypeMap, typeMap, null); } } return _lazyTypeMap; } } private MethodSymbol OverriddenMethod { get { if (ReferenceEquals(_lazyOverriddenMethod, ErrorMethodSymbol.UnknownMethod)) { Interlocked.CompareExchange(ref _lazyOverriddenMethod, this.GetOverriddenMethod(_overridingMethod), ErrorMethodSymbol.UnknownMethod); } return _lazyOverriddenMethod; } } protected abstract MethodSymbol GetOverriddenMethod(SourceOrdinaryMethodSymbol overridingMethod); } internal sealed class OverriddenMethodTypeParameterMap : OverriddenMethodTypeParameterMapBase { public OverriddenMethodTypeParameterMap(SourceOrdinaryMethodSymbol overridingMethod) : base(overridingMethod) { Debug.Assert(overridingMethod.IsOverride); } protected override MethodSymbol GetOverriddenMethod(SourceOrdinaryMethodSymbol overridingMethod) { MethodSymbol method = overridingMethod; Debug.Assert(method.IsOverride); do { method = method.OverriddenMethod; } while (((object)method != null) && method.IsOverride); // OverriddenMethod may be null in error situations. return method; } } internal sealed class ExplicitInterfaceMethodTypeParameterMap : OverriddenMethodTypeParameterMapBase { public ExplicitInterfaceMethodTypeParameterMap(SourceOrdinaryMethodSymbol implementationMethod) : base(implementationMethod) { Debug.Assert(implementationMethod.IsExplicitInterfaceImplementation); } protected override MethodSymbol GetOverriddenMethod(SourceOrdinaryMethodSymbol overridingMethod) { var explicitImplementations = overridingMethod.ExplicitInterfaceImplementations; Debug.Assert(explicitImplementations.Length <= 1); // ExplicitInterfaceImplementations may be empty in error situations. return (explicitImplementations.Length > 0) ? explicitImplementations[0] : null; } } /// <summary> /// A type parameter for a method that either overrides a base /// type method or explicitly implements an interface method. /// </summary> /// <remarks> /// Exists to copy constraints from the corresponding type parameter of an overridden method. /// </remarks> internal sealed class SourceOverridingMethodTypeParameterSymbol : SourceTypeParameterSymbolBase { private readonly OverriddenMethodTypeParameterMapBase _map; public SourceOverridingMethodTypeParameterSymbol(OverriddenMethodTypeParameterMapBase map, string name, int ordinal, ImmutableArray<Location> locations, ImmutableArray<SyntaxReference> syntaxRefs) : base(name, ordinal, locations, syntaxRefs) { _map = map; } public SourceOrdinaryMethodSymbol Owner { get { return _map.OverridingMethod; } } public override TypeParameterKind TypeParameterKind { get { return TypeParameterKind.Method; } } public override Symbol ContainingSymbol { get { return this.Owner; } } public override bool HasConstructorConstraint { get { var typeParameter = this.OverriddenTypeParameter; return ((object)typeParameter != null) && typeParameter.HasConstructorConstraint; } } public override bool HasValueTypeConstraint { get { var typeParameter = this.OverriddenTypeParameter; return ((object)typeParameter != null) && typeParameter.HasValueTypeConstraint; } } public override bool IsValueTypeFromConstraintTypes { get { var typeParameter = this.OverriddenTypeParameter; return ((object)typeParameter != null) && (typeParameter.IsValueTypeFromConstraintTypes || CalculateIsValueTypeFromConstraintTypes(ConstraintTypesNoUseSiteDiagnostics)); } } public override bool HasReferenceTypeConstraint { get { var typeParameter = this.OverriddenTypeParameter; return ((object)typeParameter != null) && typeParameter.HasReferenceTypeConstraint; } } public override bool IsReferenceTypeFromConstraintTypes { get { var typeParameter = this.OverriddenTypeParameter; return ((object)typeParameter != null) && (typeParameter.IsReferenceTypeFromConstraintTypes || CalculateIsReferenceTypeFromConstraintTypes(ConstraintTypesNoUseSiteDiagnostics)); } } internal override bool? ReferenceTypeConstraintIsNullable { get { TypeParameterSymbol typeParameter = this.OverriddenTypeParameter; return ((object)typeParameter != null) ? typeParameter.ReferenceTypeConstraintIsNullable : false; } } public override bool HasNotNullConstraint { get { return this.OverriddenTypeParameter?.HasNotNullConstraint == true; } } internal override bool? IsNotNullable { get { return this.OverriddenTypeParameter?.IsNotNullable; } } public override bool HasUnmanagedTypeConstraint { get { var typeParameter = this.OverriddenTypeParameter; return ((object)typeParameter != null) && typeParameter.HasUnmanagedTypeConstraint; } } protected override ImmutableArray<TypeParameterSymbol> ContainerTypeParameters { get { return this.Owner.TypeParameters; } } protected override TypeParameterBounds ResolveBounds(ConsList<TypeParameterSymbol> inProgress, BindingDiagnosticBag diagnostics) { var typeParameter = this.OverriddenTypeParameter; if ((object)typeParameter == null) { return null; } var map = _map.TypeMap; Debug.Assert(map != null); var constraintTypes = map.SubstituteTypes(typeParameter.ConstraintTypesNoUseSiteDiagnostics); return this.ResolveBounds(this.ContainingAssembly.CorLibrary, inProgress.Prepend(this), constraintTypes, inherited: true, this.DeclaringCompilation, diagnostics); } /// <summary> /// The type parameter to use for determining constraints. If there is a base /// method that the owner method is overriding, the corresponding type /// parameter on that method is used. Otherwise, the result is null. /// </summary> private TypeParameterSymbol OverriddenTypeParameter { get { return _map.GetOverriddenTypeParameter(this.Ordinal); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Base class for type and method type parameters. /// </summary> internal abstract class SourceTypeParameterSymbolBase : TypeParameterSymbol, IAttributeTargetSymbol { private readonly ImmutableArray<SyntaxReference> _syntaxRefs; private readonly ImmutableArray<Location> _locations; private readonly string _name; private readonly short _ordinal; private SymbolCompletionState _state; private CustomAttributesBag<CSharpAttributeData> _lazyCustomAttributesBag; private TypeParameterBounds _lazyBounds = TypeParameterBounds.Unset; protected SourceTypeParameterSymbolBase(string name, int ordinal, ImmutableArray<Location> locations, ImmutableArray<SyntaxReference> syntaxRefs) { Debug.Assert(!syntaxRefs.IsEmpty); _name = name; _ordinal = (short)ordinal; _locations = locations; _syntaxRefs = syntaxRefs; } public override ImmutableArray<Location> Locations { get { return _locations; } } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { return _syntaxRefs; } } internal ImmutableArray<SyntaxReference> SyntaxReferences { get { return _syntaxRefs; } } public override int Ordinal { get { return _ordinal; } } public override VarianceKind Variance { get { return VarianceKind.None; } } public override string Name { get { return _name; } } internal override ImmutableArray<TypeWithAnnotations> GetConstraintTypes(ConsList<TypeParameterSymbol> inProgress) { var bounds = this.GetBounds(inProgress); return (bounds != null) ? bounds.ConstraintTypes : ImmutableArray<TypeWithAnnotations>.Empty; } internal override ImmutableArray<NamedTypeSymbol> GetInterfaces(ConsList<TypeParameterSymbol> inProgress) { var bounds = this.GetBounds(inProgress); return (bounds != null) ? bounds.Interfaces : ImmutableArray<NamedTypeSymbol>.Empty; } internal override NamedTypeSymbol GetEffectiveBaseClass(ConsList<TypeParameterSymbol> inProgress) { var bounds = this.GetBounds(inProgress); return (bounds != null) ? bounds.EffectiveBaseClass : this.GetDefaultBaseType(); } internal override TypeSymbol GetDeducedBaseType(ConsList<TypeParameterSymbol> inProgress) { var bounds = this.GetBounds(inProgress); return (bounds != null) ? bounds.DeducedBaseType : this.GetDefaultBaseType(); } internal ImmutableArray<SyntaxList<AttributeListSyntax>> MergedAttributeDeclarationSyntaxLists { get { var mergedAttributesBuilder = ArrayBuilder<SyntaxList<AttributeListSyntax>>.GetInstance(); foreach (var syntaxRef in _syntaxRefs) { var syntax = (TypeParameterSyntax)syntaxRef.GetSyntax(); mergedAttributesBuilder.Add(syntax.AttributeLists); } var sourceMethod = this.ContainingSymbol as SourceOrdinaryMethodSymbol; if ((object)sourceMethod != null && sourceMethod.IsPartial) { var implementingPart = sourceMethod.SourcePartialImplementation; if ((object)implementingPart != null) { var typeParameter = (SourceTypeParameterSymbolBase)implementingPart.TypeParameters[_ordinal]; mergedAttributesBuilder.AddRange(typeParameter.MergedAttributeDeclarationSyntaxLists); } } return mergedAttributesBuilder.ToImmutableAndFree(); } } IAttributeTargetSymbol IAttributeTargetSymbol.AttributesOwner { get { return this; } } AttributeLocation IAttributeTargetSymbol.DefaultAttributeLocation { get { return AttributeLocation.TypeParameter; } } AttributeLocation IAttributeTargetSymbol.AllowedAttributeLocations { get { return AttributeLocation.TypeParameter; } } /// <summary> /// Gets the attributes applied on this symbol. /// Returns an empty array if there are no attributes. /// </summary> /// <remarks> /// NOTE: This method should always be kept as a sealed override. /// If you want to override attribute binding logic for a sub-class, then override <see cref="GetAttributesBag"/> method. /// </remarks> public sealed override ImmutableArray<CSharpAttributeData> GetAttributes() { return this.GetAttributesBag().Attributes; } /// <summary> /// Returns a bag of applied custom attributes and data decoded from well-known attributes. Returns null if there are no attributes applied on the symbol. /// </summary> /// <remarks> /// Forces binding and decoding of attributes. /// </remarks> internal virtual CustomAttributesBag<CSharpAttributeData> GetAttributesBag() { if (_lazyCustomAttributesBag == null || !_lazyCustomAttributesBag.IsSealed) { bool lazyAttributesStored = false; var sourceMethod = this.ContainingSymbol as SourceOrdinaryMethodSymbol; if ((object)sourceMethod == null || (object)sourceMethod.SourcePartialDefinition == null) { lazyAttributesStored = LoadAndValidateAttributes( OneOrMany.Create(this.MergedAttributeDeclarationSyntaxLists), ref _lazyCustomAttributesBag, binderOpt: (ContainingSymbol as LocalFunctionSymbol)?.SignatureBinder); } else { var typeParameter = (SourceTypeParameterSymbolBase)sourceMethod.SourcePartialDefinition.TypeParameters[_ordinal]; CustomAttributesBag<CSharpAttributeData> attributesBag = typeParameter.GetAttributesBag(); lazyAttributesStored = Interlocked.CompareExchange(ref _lazyCustomAttributesBag, attributesBag, null) == null; } if (lazyAttributesStored) { _state.NotePartComplete(CompletionPart.Attributes); } } return _lazyCustomAttributesBag; } internal override void EnsureAllConstraintsAreResolved() { if (!_lazyBounds.IsSet()) { EnsureAllConstraintsAreResolved(this.ContainerTypeParameters); } } protected abstract ImmutableArray<TypeParameterSymbol> ContainerTypeParameters { get; } private TypeParameterBounds GetBounds(ConsList<TypeParameterSymbol> inProgress) { Debug.Assert(!inProgress.ContainsReference(this)); Debug.Assert(!inProgress.Any() || ReferenceEquals(inProgress.Head.ContainingSymbol, this.ContainingSymbol)); if (!_lazyBounds.IsSet()) { var diagnostics = BindingDiagnosticBag.GetInstance(); var bounds = this.ResolveBounds(inProgress, diagnostics); if (ReferenceEquals(Interlocked.CompareExchange(ref _lazyBounds, bounds, TypeParameterBounds.Unset), TypeParameterBounds.Unset)) { this.CheckConstraintTypeConstraints(diagnostics); this.CheckUnmanagedConstraint(diagnostics); this.EnsureAttributesFromConstraints(diagnostics); this.AddDeclarationDiagnostics(diagnostics); _state.NotePartComplete(CompletionPart.TypeParameterConstraints); } diagnostics.Free(); } return _lazyBounds; } protected abstract TypeParameterBounds ResolveBounds(ConsList<TypeParameterSymbol> inProgress, BindingDiagnosticBag diagnostics); /// <summary> /// Check constraints of generic types referenced in constraint types. For instance, /// with "interface I&lt;T&gt; where T : I&lt;T&gt; {}", check T satisfies constraints /// on I&lt;T&gt;. Those constraints are not checked when binding ConstraintTypes /// since ConstraintTypes has not been set on I&lt;T&gt; at that point. /// </summary> private void CheckConstraintTypeConstraints(BindingDiagnosticBag diagnostics) { var constraintTypes = this.ConstraintTypesNoUseSiteDiagnostics; if (constraintTypes.Length == 0) { return; } var args = new ConstraintsHelper.CheckConstraintsArgsBoxed(DeclaringCompilation, new TypeConversions(ContainingAssembly.CorLibrary), _locations[0], diagnostics); foreach (var constraintType in constraintTypes) { if (!diagnostics.ReportUseSite(constraintType.Type, args.Args.Location)) { constraintType.Type.CheckAllConstraints(args); } } } private void CheckUnmanagedConstraint(BindingDiagnosticBag diagnostics) { if (this.HasUnmanagedTypeConstraint) { DeclaringCompilation.EnsureIsUnmanagedAttributeExists(diagnostics, this.GetNonNullSyntaxNode().Location, ModifyCompilationForAttributeEmbedding()); } } private bool ModifyCompilationForAttributeEmbedding() { bool modifyCompilation; switch (this.ContainingSymbol) { case SourceOrdinaryMethodSymbol _: case SourceMemberContainerTypeSymbol _: modifyCompilation = true; break; case LocalFunctionSymbol _: modifyCompilation = false; break; default: throw ExceptionUtilities.UnexpectedValue(this.ContainingSymbol); } return modifyCompilation; } private void EnsureAttributesFromConstraints(BindingDiagnosticBag diagnostics) { if (ConstraintTypesNoUseSiteDiagnostics.Any(t => t.ContainsNativeInteger())) { DeclaringCompilation.EnsureNativeIntegerAttributeExists(diagnostics, getLocation(), ModifyCompilationForAttributeEmbedding()); } if (ConstraintsNeedNullableAttribute()) { DeclaringCompilation.EnsureNullableAttributeExists(diagnostics, getLocation(), ModifyCompilationForAttributeEmbedding()); } Location getLocation() => this.GetNonNullSyntaxNode().Location; } // See https://github.com/dotnet/roslyn/blob/main/docs/features/nullable-metadata.md internal bool ConstraintsNeedNullableAttribute() { if (!DeclaringCompilation.ShouldEmitNullableAttributes(this)) { return false; } if (this.HasReferenceTypeConstraint && this.ReferenceTypeConstraintIsNullable != null) { return true; } if (this.ConstraintTypesNoUseSiteDiagnostics.Any(c => c.NeedsNullableAttribute())) { return true; } if (this.HasNotNullConstraint) { return true; } return !this.HasReferenceTypeConstraint && !this.HasValueTypeConstraint && this.ConstraintTypesNoUseSiteDiagnostics.IsEmpty && this.IsNotNullable == false; } private NamedTypeSymbol GetDefaultBaseType() { return this.ContainingAssembly.GetSpecialType(SpecialType.System_Object); } internal override void ForceComplete(SourceLocation locationOpt, CancellationToken cancellationToken) { while (true) { cancellationToken.ThrowIfCancellationRequested(); var incompletePart = _state.NextIncompletePart; switch (incompletePart) { case CompletionPart.Attributes: GetAttributes(); break; case CompletionPart.TypeParameterConstraints: var constraintTypes = this.ConstraintTypesNoUseSiteDiagnostics; // Nested type parameter references might not be valid in error scenarios. //Debug.Assert(this.ContainingSymbol.IsContainingSymbolOfAllTypeParameters(this.ConstraintTypes)); //Debug.Assert(this.ContainingSymbol.IsContainingSymbolOfAllTypeParameters(ImmutableArray<TypeSymbol>.CreateFrom(this.Interfaces))); Debug.Assert(this.ContainingSymbol.IsContainingSymbolOfAllTypeParameters(this.EffectiveBaseClassNoUseSiteDiagnostics)); Debug.Assert(this.ContainingSymbol.IsContainingSymbolOfAllTypeParameters(this.DeducedBaseTypeNoUseSiteDiagnostics)); break; case CompletionPart.None: return; default: // any other values are completion parts intended for other kinds of symbols _state.NotePartComplete(CompletionPart.All & ~CompletionPart.TypeParameterSymbolAll); break; } _state.SpinWaitComplete(incompletePart, cancellationToken); } } internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedAttributes(moduleBuilder, ref attributes); if (this.HasUnmanagedTypeConstraint) { AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeIsUnmanagedAttribute(this)); } var compilation = DeclaringCompilation; if (compilation.ShouldEmitNullableAttributes(this)) { AddSynthesizedAttribute( ref attributes, moduleBuilder.SynthesizeNullableAttributeIfNecessary(GetNullableContextValue(), GetSynthesizedNullableAttributeValue())); } } internal byte GetSynthesizedNullableAttributeValue() { if (this.HasReferenceTypeConstraint) { switch (this.ReferenceTypeConstraintIsNullable) { case true: return NullableAnnotationExtensions.AnnotatedAttributeValue; case false: return NullableAnnotationExtensions.NotAnnotatedAttributeValue; } } else if (this.HasNotNullConstraint) { return NullableAnnotationExtensions.NotAnnotatedAttributeValue; } else if (!this.HasValueTypeConstraint && this.ConstraintTypesNoUseSiteDiagnostics.IsEmpty && this.IsNotNullable == false) { return NullableAnnotationExtensions.AnnotatedAttributeValue; } return NullableAnnotationExtensions.ObliviousAttributeValue; } internal sealed override void DecodeWellKnownAttribute(ref DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments) { Debug.Assert((object)arguments.AttributeSyntaxOpt != null); Debug.Assert(arguments.Diagnostics is BindingDiagnosticBag); var attribute = arguments.Attribute; Debug.Assert(!attribute.HasErrors); Debug.Assert(arguments.SymbolPart == AttributeLocation.None); if (attribute.IsTargetAttribute(this, AttributeDescription.NullableAttribute)) { // NullableAttribute should not be set explicitly. ((BindingDiagnosticBag)arguments.Diagnostics).Add(ErrorCode.ERR_ExplicitNullableAttribute, arguments.AttributeSyntaxOpt.Location); } base.DecodeWellKnownAttribute(ref arguments); } protected bool? CalculateReferenceTypeConstraintIsNullable(TypeParameterConstraintKind constraints) { if ((constraints & TypeParameterConstraintKind.ReferenceType) == 0) { return false; } switch (constraints & TypeParameterConstraintKind.AllReferenceTypeKinds) { case TypeParameterConstraintKind.NullableReferenceType: return true; case TypeParameterConstraintKind.NotNullableReferenceType: return false; } return null; } } internal sealed class SourceTypeParameterSymbol : SourceTypeParameterSymbolBase { private readonly SourceNamedTypeSymbol _owner; private readonly VarianceKind _varianceKind; public SourceTypeParameterSymbol(SourceNamedTypeSymbol owner, string name, int ordinal, VarianceKind varianceKind, ImmutableArray<Location> locations, ImmutableArray<SyntaxReference> syntaxRefs) : base(name, ordinal, locations, syntaxRefs) { _owner = owner; _varianceKind = varianceKind; } public override TypeParameterKind TypeParameterKind { get { return TypeParameterKind.Type; } } public override Symbol ContainingSymbol { get { return _owner; } } public override VarianceKind Variance { get { return _varianceKind; } } public override bool HasConstructorConstraint { get { var constraints = this.GetConstraintKinds(); return (constraints & TypeParameterConstraintKind.Constructor) != 0; } } public override bool HasValueTypeConstraint { get { var constraints = this.GetConstraintKinds(); return (constraints & TypeParameterConstraintKind.AllValueTypeKinds) != 0; } } public override bool IsValueTypeFromConstraintTypes { get { Debug.Assert(!HasValueTypeConstraint); var constraints = this.GetConstraintKinds(); return (constraints & TypeParameterConstraintKind.ValueTypeFromConstraintTypes) != 0; } } public override bool HasReferenceTypeConstraint { get { var constraints = this.GetConstraintKinds(); return (constraints & TypeParameterConstraintKind.ReferenceType) != 0; } } public override bool IsReferenceTypeFromConstraintTypes { get { var constraints = this.GetConstraintKinds(); return (constraints & TypeParameterConstraintKind.ReferenceTypeFromConstraintTypes) != 0; } } internal override bool? ReferenceTypeConstraintIsNullable { get { return CalculateReferenceTypeConstraintIsNullable(this.GetConstraintKinds()); } } public override bool HasNotNullConstraint { get { var constraints = this.GetConstraintKinds(); return (constraints & TypeParameterConstraintKind.NotNull) != 0; } } internal override bool? IsNotNullable { get { if ((this.GetConstraintKinds() & TypeParameterConstraintKind.ObliviousNullabilityIfReferenceType) != 0) { return null; } return CalculateIsNotNullable(); } } public override bool HasUnmanagedTypeConstraint { get { var constraints = this.GetConstraintKinds(); return (constraints & TypeParameterConstraintKind.Unmanaged) != 0; } } protected override ImmutableArray<TypeParameterSymbol> ContainerTypeParameters { get { return _owner.TypeParameters; } } protected override TypeParameterBounds ResolveBounds(ConsList<TypeParameterSymbol> inProgress, BindingDiagnosticBag diagnostics) { var constraintTypes = _owner.GetTypeParameterConstraintTypes(this.Ordinal); if (constraintTypes.IsEmpty && GetConstraintKinds() == TypeParameterConstraintKind.None) { return null; } return this.ResolveBounds(this.ContainingAssembly.CorLibrary, inProgress.Prepend(this), constraintTypes, inherited: false, this.DeclaringCompilation, diagnostics); } private TypeParameterConstraintKind GetConstraintKinds() { return _owner.GetTypeParameterConstraintKind(this.Ordinal); } } internal sealed class SourceMethodTypeParameterSymbol : SourceTypeParameterSymbolBase { private readonly SourceMethodSymbol _owner; public SourceMethodTypeParameterSymbol(SourceMethodSymbol owner, string name, int ordinal, ImmutableArray<Location> locations, ImmutableArray<SyntaxReference> syntaxRefs) : base(name, ordinal, locations, syntaxRefs) { _owner = owner; } internal override void AddDeclarationDiagnostics(BindingDiagnosticBag diagnostics) => _owner.AddDeclarationDiagnostics(diagnostics); public override TypeParameterKind TypeParameterKind { get { return TypeParameterKind.Method; } } public override Symbol ContainingSymbol { get { return _owner; } } public override bool HasConstructorConstraint { get { var constraints = this.GetConstraintKinds(); return (constraints & TypeParameterConstraintKind.Constructor) != 0; } } public override bool HasValueTypeConstraint { get { var constraints = this.GetConstraintKinds(); return (constraints & TypeParameterConstraintKind.AllValueTypeKinds) != 0; } } public override bool IsValueTypeFromConstraintTypes { get { Debug.Assert(!HasValueTypeConstraint); var constraints = this.GetConstraintKinds(); return (constraints & TypeParameterConstraintKind.ValueTypeFromConstraintTypes) != 0; } } public override bool HasReferenceTypeConstraint { get { var constraints = this.GetConstraintKinds(); return (constraints & TypeParameterConstraintKind.ReferenceType) != 0; } } public override bool IsReferenceTypeFromConstraintTypes { get { var constraints = this.GetConstraintKinds(); return (constraints & TypeParameterConstraintKind.ReferenceTypeFromConstraintTypes) != 0; } } public override bool HasNotNullConstraint { get { var constraints = this.GetConstraintKinds(); return (constraints & TypeParameterConstraintKind.NotNull) != 0; } } internal override bool? ReferenceTypeConstraintIsNullable { get { return CalculateReferenceTypeConstraintIsNullable(this.GetConstraintKinds()); } } internal override bool? IsNotNullable { get { if ((this.GetConstraintKinds() & TypeParameterConstraintKind.ObliviousNullabilityIfReferenceType) != 0) { return null; } return CalculateIsNotNullable(); } } public override bool HasUnmanagedTypeConstraint { get { var constraints = this.GetConstraintKinds(); return (constraints & TypeParameterConstraintKind.Unmanaged) != 0; } } protected override ImmutableArray<TypeParameterSymbol> ContainerTypeParameters { get { return _owner.TypeParameters; } } protected override TypeParameterBounds ResolveBounds(ConsList<TypeParameterSymbol> inProgress, BindingDiagnosticBag diagnostics) { var constraints = _owner.GetTypeParameterConstraintTypes(); var constraintTypes = constraints.IsEmpty ? ImmutableArray<TypeWithAnnotations>.Empty : constraints[Ordinal]; if (constraintTypes.IsEmpty && GetConstraintKinds() == TypeParameterConstraintKind.None) { return null; } return this.ResolveBounds(this.ContainingAssembly.CorLibrary, inProgress.Prepend(this), constraintTypes, inherited: false, this.DeclaringCompilation, diagnostics); } private TypeParameterConstraintKind GetConstraintKinds() { var constraintKinds = _owner.GetTypeParameterConstraintKinds(); return constraintKinds.IsEmpty ? TypeParameterConstraintKind.None : constraintKinds[Ordinal]; } } /// <summary> /// A map shared by all type parameters for an overriding method or a method /// that explicitly implements an interface. The map caches the overridden method /// and a type map from overridden type parameters to overriding type parameters. /// </summary> internal abstract class OverriddenMethodTypeParameterMapBase { // Method representing overriding or explicit implementation. private readonly SourceOrdinaryMethodSymbol _overridingMethod; // Type map shared by all type parameters for this explicit implementation. private TypeMap _lazyTypeMap; // Overridden or explicitly implemented method. May be null in error cases. private MethodSymbol _lazyOverriddenMethod = ErrorMethodSymbol.UnknownMethod; protected OverriddenMethodTypeParameterMapBase(SourceOrdinaryMethodSymbol overridingMethod) { _overridingMethod = overridingMethod; } public SourceOrdinaryMethodSymbol OverridingMethod { get { return _overridingMethod; } } public TypeParameterSymbol GetOverriddenTypeParameter(int ordinal) { var overriddenMethod = this.OverriddenMethod; return ((object)overriddenMethod != null) ? overriddenMethod.TypeParameters[ordinal] : null; } public TypeMap TypeMap { get { if (_lazyTypeMap == null) { var overriddenMethod = this.OverriddenMethod; if ((object)overriddenMethod != null) { var overriddenTypeParameters = overriddenMethod.TypeParameters; var overridingTypeParameters = _overridingMethod.TypeParameters; Debug.Assert(overriddenTypeParameters.Length == overridingTypeParameters.Length); var typeMap = new TypeMap(overriddenTypeParameters, overridingTypeParameters, allowAlpha: true); Interlocked.CompareExchange(ref _lazyTypeMap, typeMap, null); } } return _lazyTypeMap; } } private MethodSymbol OverriddenMethod { get { if (ReferenceEquals(_lazyOverriddenMethod, ErrorMethodSymbol.UnknownMethod)) { Interlocked.CompareExchange(ref _lazyOverriddenMethod, this.GetOverriddenMethod(_overridingMethod), ErrorMethodSymbol.UnknownMethod); } return _lazyOverriddenMethod; } } protected abstract MethodSymbol GetOverriddenMethod(SourceOrdinaryMethodSymbol overridingMethod); } internal sealed class OverriddenMethodTypeParameterMap : OverriddenMethodTypeParameterMapBase { public OverriddenMethodTypeParameterMap(SourceOrdinaryMethodSymbol overridingMethod) : base(overridingMethod) { Debug.Assert(overridingMethod.IsOverride); } protected override MethodSymbol GetOverriddenMethod(SourceOrdinaryMethodSymbol overridingMethod) { MethodSymbol method = overridingMethod; Debug.Assert(method.IsOverride); do { method = method.OverriddenMethod; } while (((object)method != null) && method.IsOverride); // OverriddenMethod may be null in error situations. return method; } } internal sealed class ExplicitInterfaceMethodTypeParameterMap : OverriddenMethodTypeParameterMapBase { public ExplicitInterfaceMethodTypeParameterMap(SourceOrdinaryMethodSymbol implementationMethod) : base(implementationMethod) { Debug.Assert(implementationMethod.IsExplicitInterfaceImplementation); } protected override MethodSymbol GetOverriddenMethod(SourceOrdinaryMethodSymbol overridingMethod) { var explicitImplementations = overridingMethod.ExplicitInterfaceImplementations; Debug.Assert(explicitImplementations.Length <= 1); // ExplicitInterfaceImplementations may be empty in error situations. return (explicitImplementations.Length > 0) ? explicitImplementations[0] : null; } } /// <summary> /// A type parameter for a method that either overrides a base /// type method or explicitly implements an interface method. /// </summary> /// <remarks> /// Exists to copy constraints from the corresponding type parameter of an overridden method. /// </remarks> internal sealed class SourceOverridingMethodTypeParameterSymbol : SourceTypeParameterSymbolBase { private readonly OverriddenMethodTypeParameterMapBase _map; public SourceOverridingMethodTypeParameterSymbol(OverriddenMethodTypeParameterMapBase map, string name, int ordinal, ImmutableArray<Location> locations, ImmutableArray<SyntaxReference> syntaxRefs) : base(name, ordinal, locations, syntaxRefs) { _map = map; } public SourceOrdinaryMethodSymbol Owner { get { return _map.OverridingMethod; } } public override TypeParameterKind TypeParameterKind { get { return TypeParameterKind.Method; } } public override Symbol ContainingSymbol { get { return this.Owner; } } public override bool HasConstructorConstraint { get { var typeParameter = this.OverriddenTypeParameter; return ((object)typeParameter != null) && typeParameter.HasConstructorConstraint; } } public override bool HasValueTypeConstraint { get { var typeParameter = this.OverriddenTypeParameter; return ((object)typeParameter != null) && typeParameter.HasValueTypeConstraint; } } public override bool IsValueTypeFromConstraintTypes { get { var typeParameter = this.OverriddenTypeParameter; return ((object)typeParameter != null) && (typeParameter.IsValueTypeFromConstraintTypes || CalculateIsValueTypeFromConstraintTypes(ConstraintTypesNoUseSiteDiagnostics)); } } public override bool HasReferenceTypeConstraint { get { var typeParameter = this.OverriddenTypeParameter; return ((object)typeParameter != null) && typeParameter.HasReferenceTypeConstraint; } } public override bool IsReferenceTypeFromConstraintTypes { get { var typeParameter = this.OverriddenTypeParameter; return ((object)typeParameter != null) && (typeParameter.IsReferenceTypeFromConstraintTypes || CalculateIsReferenceTypeFromConstraintTypes(ConstraintTypesNoUseSiteDiagnostics)); } } internal override bool? ReferenceTypeConstraintIsNullable { get { TypeParameterSymbol typeParameter = this.OverriddenTypeParameter; return ((object)typeParameter != null) ? typeParameter.ReferenceTypeConstraintIsNullable : false; } } public override bool HasNotNullConstraint { get { return this.OverriddenTypeParameter?.HasNotNullConstraint == true; } } internal override bool? IsNotNullable { get { return this.OverriddenTypeParameter?.IsNotNullable; } } public override bool HasUnmanagedTypeConstraint { get { var typeParameter = this.OverriddenTypeParameter; return ((object)typeParameter != null) && typeParameter.HasUnmanagedTypeConstraint; } } protected override ImmutableArray<TypeParameterSymbol> ContainerTypeParameters { get { return this.Owner.TypeParameters; } } protected override TypeParameterBounds ResolveBounds(ConsList<TypeParameterSymbol> inProgress, BindingDiagnosticBag diagnostics) { var typeParameter = this.OverriddenTypeParameter; if ((object)typeParameter == null) { return null; } var map = _map.TypeMap; Debug.Assert(map != null); var constraintTypes = map.SubstituteTypes(typeParameter.ConstraintTypesNoUseSiteDiagnostics); return this.ResolveBounds(this.ContainingAssembly.CorLibrary, inProgress.Prepend(this), constraintTypes, inherited: true, this.DeclaringCompilation, diagnostics); } /// <summary> /// The type parameter to use for determining constraints. If there is a base /// method that the owner method is overriding, the corresponding type /// parameter on that method is used. Otherwise, the result is null. /// </summary> private TypeParameterSymbol OverriddenTypeParameter { get { return _map.GetOverriddenTypeParameter(this.Ordinal); } } } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/Features/Core/Portable/ConvertIfToSwitch/AbstractConvertIfToSwitchCodeRefactoringProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ConvertIfToSwitch { internal abstract partial class AbstractConvertIfToSwitchCodeRefactoringProvider< TIfStatementSyntax, TExpressionSyntax, TIsExpressionSyntax, TPatternSyntax> : CodeRefactoringProvider { public abstract string GetTitle(bool forSwitchExpression); public abstract Analyzer CreateAnalyzer(ISyntaxFacts syntaxFacts, ParseOptions options); public sealed override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var (document, _, cancellationToken) = context; if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles) { return; } var ifStatement = await context.TryGetRelevantNodeAsync<TIfStatementSyntax>().ConfigureAwait(false); if (ifStatement == null || ifStatement.GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)) { return; } var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var ifOperation = semanticModel.GetOperation(ifStatement); if (ifOperation is not IConditionalOperation { Parent: IBlockOperation parentBlock }) { return; } var operations = parentBlock.Operations; var index = operations.IndexOf(ifOperation); var syntaxFactsService = document.GetLanguageService<ISyntaxFactsService>(); if (syntaxFactsService == null) { return; } var analyzer = CreateAnalyzer(syntaxFactsService, ifStatement.SyntaxTree.Options); var (sections, target) = analyzer.AnalyzeIfStatementSequence(operations.AsSpan()[index..]); if (sections.IsDefaultOrEmpty) { return; } // To prevent noisiness we don't offer this unless we're going to generate at least // two switch labels. It can be quite annoying to basically have this offered // on pretty much any simple 'if' like "if (a == 0)" or "if (x == null)". In these // cases, the converted code just looks and feels worse, and it ends up causing the // lightbulb to appear too much. // // This does mean that if someone has a simple if, and is about to add a lot more // cases, and says to themselves "let me convert this to a switch first!", then they'll // be out of luck. However, I believe the core value here is in taking existing large // if-chains/checks and easily converting them over to a switch. So not offering the // feature on simple if-statements seems like an acceptable compromise to take to ensure // the overall user experience isn't degraded. var labelCount = sections.Sum(section => section.Labels.IsDefault ? 1 : section.Labels.Length); if (labelCount < 2) { return; } context.RegisterRefactoring( new MyCodeAction(GetTitle(forSwitchExpression: false), c => UpdateDocumentAsync(document, target, ifStatement, sections, analyzer.Features, convertToSwitchExpression: false, c), "SwitchStatement"), ifStatement.Span); if (analyzer.Supports(Feature.SwitchExpression) && CanConvertToSwitchExpression(analyzer.Supports(Feature.OrPattern), sections)) { context.RegisterRefactoring( new MyCodeAction(GetTitle(forSwitchExpression: true), c => UpdateDocumentAsync(document, target, ifStatement, sections, analyzer.Features, convertToSwitchExpression: true, c), "SwitchExpression"), ifStatement.Span); } } private static bool CanConvertToSwitchExpression( bool supportsOrPattern, ImmutableArray<AnalyzedSwitchSection> sections) { // There must be a default case for an exhaustive switch expression if (!sections.Any(section => section.Labels.IsDefault)) return false; // There must be at least one return statement if (!sections.Any(section => GetSwitchArmKind(section.Body) == OperationKind.Return)) return false; if (!sections.All(section => CanConvertSectionForSwitchExpression(supportsOrPattern, section))) return false; return true; static OperationKind GetSwitchArmKind(IOperation op) { switch (op) { case IReturnOperation { ReturnedValue: { } }: case IThrowOperation { Exception: { } }: return op.Kind; case IBlockOperation { Operations: { Length: 1 } statements }: return GetSwitchArmKind(statements[0]); } return default; } static bool CanConvertSectionForSwitchExpression(bool supportsOrPattern, AnalyzedSwitchSection section) { // All arms must be convertible to a switch arm if (GetSwitchArmKind(section.Body) == default) return false; // Default label can trivially be converted to a switch arm. if (section.Labels.IsDefault) return true; // Single label case can trivially be converted to a switch arm. if (section.Labels.Length == 1) return true; if (section.Labels.Length == 0) { Debug.Fail("How did we not get any labels?"); return false; } // If there are two or more labels, we can support this as long as the language supports 'or' patterns // and as long as no label has any guards. return supportsOrPattern && section.Labels.All(label => label.Guards.IsDefaultOrEmpty); } } private sealed class MyCodeAction : CodeAction.DocumentChangeAction { public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument, string equivalenceKey) : base(title, createChangedDocument, equivalenceKey) { } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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 System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ConvertIfToSwitch { internal abstract partial class AbstractConvertIfToSwitchCodeRefactoringProvider< TIfStatementSyntax, TExpressionSyntax, TIsExpressionSyntax, TPatternSyntax> : CodeRefactoringProvider { public abstract string GetTitle(bool forSwitchExpression); public abstract Analyzer CreateAnalyzer(ISyntaxFacts syntaxFacts, ParseOptions options); public sealed override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var (document, _, cancellationToken) = context; if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles) { return; } var ifStatement = await context.TryGetRelevantNodeAsync<TIfStatementSyntax>().ConfigureAwait(false); if (ifStatement == null || ifStatement.GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)) { return; } var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var ifOperation = semanticModel.GetOperation(ifStatement); if (ifOperation is not IConditionalOperation { Parent: IBlockOperation parentBlock }) { return; } var operations = parentBlock.Operations; var index = operations.IndexOf(ifOperation); var syntaxFactsService = document.GetLanguageService<ISyntaxFactsService>(); if (syntaxFactsService == null) { return; } var analyzer = CreateAnalyzer(syntaxFactsService, ifStatement.SyntaxTree.Options); var (sections, target) = analyzer.AnalyzeIfStatementSequence(operations.AsSpan()[index..]); if (sections.IsDefaultOrEmpty) { return; } // To prevent noisiness we don't offer this unless we're going to generate at least // two switch labels. It can be quite annoying to basically have this offered // on pretty much any simple 'if' like "if (a == 0)" or "if (x == null)". In these // cases, the converted code just looks and feels worse, and it ends up causing the // lightbulb to appear too much. // // This does mean that if someone has a simple if, and is about to add a lot more // cases, and says to themselves "let me convert this to a switch first!", then they'll // be out of luck. However, I believe the core value here is in taking existing large // if-chains/checks and easily converting them over to a switch. So not offering the // feature on simple if-statements seems like an acceptable compromise to take to ensure // the overall user experience isn't degraded. var labelCount = sections.Sum(section => section.Labels.IsDefault ? 1 : section.Labels.Length); if (labelCount < 2) { return; } context.RegisterRefactoring( new MyCodeAction(GetTitle(forSwitchExpression: false), c => UpdateDocumentAsync(document, target, ifStatement, sections, analyzer.Features, convertToSwitchExpression: false, c), "SwitchStatement"), ifStatement.Span); if (analyzer.Supports(Feature.SwitchExpression) && CanConvertToSwitchExpression(analyzer.Supports(Feature.OrPattern), sections)) { context.RegisterRefactoring( new MyCodeAction(GetTitle(forSwitchExpression: true), c => UpdateDocumentAsync(document, target, ifStatement, sections, analyzer.Features, convertToSwitchExpression: true, c), "SwitchExpression"), ifStatement.Span); } } private static bool CanConvertToSwitchExpression( bool supportsOrPattern, ImmutableArray<AnalyzedSwitchSection> sections) { // There must be a default case for an exhaustive switch expression if (!sections.Any(section => section.Labels.IsDefault)) return false; // There must be at least one return statement if (!sections.Any(section => GetSwitchArmKind(section.Body) == OperationKind.Return)) return false; if (!sections.All(section => CanConvertSectionForSwitchExpression(supportsOrPattern, section))) return false; return true; static OperationKind GetSwitchArmKind(IOperation op) { switch (op) { case IReturnOperation { ReturnedValue: { } }: case IThrowOperation { Exception: { } }: return op.Kind; case IBlockOperation { Operations: { Length: 1 } statements }: return GetSwitchArmKind(statements[0]); } return default; } static bool CanConvertSectionForSwitchExpression(bool supportsOrPattern, AnalyzedSwitchSection section) { // All arms must be convertible to a switch arm if (GetSwitchArmKind(section.Body) == default) return false; // Default label can trivially be converted to a switch arm. if (section.Labels.IsDefault) return true; // Single label case can trivially be converted to a switch arm. if (section.Labels.Length == 1) return true; if (section.Labels.Length == 0) { Debug.Fail("How did we not get any labels?"); return false; } // If there are two or more labels, we can support this as long as the language supports 'or' patterns // and as long as no label has any guards. return supportsOrPattern && section.Labels.All(label => label.Guards.IsDefaultOrEmpty); } } private sealed class MyCodeAction : CodeAction.DocumentChangeAction { public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument, string equivalenceKey) : base(title, createChangedDocument, equivalenceKey) { } } } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/VisualStudio/Core/Impl/CodeModel/CodeModelProjectCache.CacheEntry.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel { internal sealed partial class CodeModelProjectCache { private struct CacheEntry { // NOTE: The logic here is a little bit tricky. We can't just keep a WeakReference to // something like a ComHandle, since it's not something that our clients keep alive. // instead, we keep a weak reference to the inner managed object, which we know will // always be alive if the outer aggregate is alive. We can't just keep a WeakReference // to the RCW for the outer object either, since in cases where we have a DCOM or native // client, the RCW will be cleaned up, even though there is still a native reference // to the underlying native outer object. // // Instead we make use of an implementation detail of the way the CLR's COM aggregation // works. Namely, if all references to the aggregated object are released, the CLR // responds to QI's for IUnknown with a different object. So, we store the original // value, when we know that we have a client, and then we use that to compare to see // if we still have a client alive. // // NOTE: This is _NOT_ AddRef'd. We use it just to store the integer value of the // IUnknown for comparison purposes. private readonly WeakComHandle<EnvDTE80.FileCodeModel2, FileCodeModel> _fileCodeModelWeakComHandle; public CacheEntry(ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel> handle) => _fileCodeModelWeakComHandle = new WeakComHandle<EnvDTE80.FileCodeModel2, FileCodeModel>(handle); public EnvDTE80.FileCodeModel2 FileCodeModelRcw { get { return _fileCodeModelWeakComHandle.ComAggregateObject; } } internal bool TryGetFileCodeModelInstanceWithoutCaringWhetherRcwIsAlive(out FileCodeModel fileCodeModel) => _fileCodeModelWeakComHandle.TryGetManagedObjectWithoutCaringWhetherNativeObjectIsAlive(out fileCodeModel); public ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel>? ComHandle { get { return _fileCodeModelWeakComHandle.ComHandle; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel { internal sealed partial class CodeModelProjectCache { private struct CacheEntry { // NOTE: The logic here is a little bit tricky. We can't just keep a WeakReference to // something like a ComHandle, since it's not something that our clients keep alive. // instead, we keep a weak reference to the inner managed object, which we know will // always be alive if the outer aggregate is alive. We can't just keep a WeakReference // to the RCW for the outer object either, since in cases where we have a DCOM or native // client, the RCW will be cleaned up, even though there is still a native reference // to the underlying native outer object. // // Instead we make use of an implementation detail of the way the CLR's COM aggregation // works. Namely, if all references to the aggregated object are released, the CLR // responds to QI's for IUnknown with a different object. So, we store the original // value, when we know that we have a client, and then we use that to compare to see // if we still have a client alive. // // NOTE: This is _NOT_ AddRef'd. We use it just to store the integer value of the // IUnknown for comparison purposes. private readonly WeakComHandle<EnvDTE80.FileCodeModel2, FileCodeModel> _fileCodeModelWeakComHandle; public CacheEntry(ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel> handle) => _fileCodeModelWeakComHandle = new WeakComHandle<EnvDTE80.FileCodeModel2, FileCodeModel>(handle); public EnvDTE80.FileCodeModel2 FileCodeModelRcw { get { return _fileCodeModelWeakComHandle.ComAggregateObject; } } internal bool TryGetFileCodeModelInstanceWithoutCaringWhetherRcwIsAlive(out FileCodeModel fileCodeModel) => _fileCodeModelWeakComHandle.TryGetManagedObjectWithoutCaringWhetherNativeObjectIsAlive(out fileCodeModel); public ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel>? ComHandle { get { return _fileCodeModelWeakComHandle.ComHandle; } } } } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/VisualStudio/Xaml/Impl/Features/Diagnostics/XamlDiagnosticReport.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; namespace Microsoft.VisualStudio.LanguageServices.Xaml.Features.Diagnostics { internal class XamlDiagnosticReport { public string? ResultId { get; set; } public ImmutableArray<XamlDiagnostic>? Diagnostics { get; set; } public XamlDiagnosticReport(string? resultId = null, ImmutableArray<XamlDiagnostic>? diagnostics = null) { this.ResultId = resultId; this.Diagnostics = diagnostics; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; namespace Microsoft.VisualStudio.LanguageServices.Xaml.Features.Diagnostics { internal class XamlDiagnosticReport { public string? ResultId { get; set; } public ImmutableArray<XamlDiagnostic>? Diagnostics { get; set; } public XamlDiagnosticReport(string? resultId = null, ImmutableArray<XamlDiagnostic>? diagnostics = null) { this.ResultId = resultId; this.Diagnostics = diagnostics; } } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/Workspaces/Remote/Core/GlobalNotificationRemoteDeliveryService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Host; using Microsoft.CodeAnalysis.Notification; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Remote { /// <summary> /// Delivers global notifications to remote services. /// </summary> internal sealed class GlobalNotificationRemoteDeliveryService : IDisposable { private enum GlobalNotificationState { NotStarted, Started } /// <summary> /// Lock for the <see cref="_globalNotificationsTask"/> task chain. Each time we hear /// about a global operation starting or stopping (i.e. a build) we will '.ContinueWith' /// this task chain with a new notification to the OOP side. This way all the messages /// are properly serialized and appear in the right order (i.e. we don't hear about a /// stop prior to hearing about the relevant start). /// </summary> private readonly object _globalNotificationsGate = new object(); private Task<GlobalNotificationState> _globalNotificationsTask = Task.FromResult(GlobalNotificationState.NotStarted); private readonly HostWorkspaceServices _services; private readonly CancellationToken _cancellationToken; public GlobalNotificationRemoteDeliveryService(HostWorkspaceServices services, CancellationToken cancellationToken) { _services = services; _cancellationToken = cancellationToken; RegisterGlobalOperationNotifications(); } public void Dispose() { UnregisterGlobalOperationNotifications(); } private void RegisterGlobalOperationNotifications() { var globalOperationService = _services.GetService<IGlobalOperationNotificationService>(); if (globalOperationService != null) { globalOperationService.Started += OnGlobalOperationStarted; globalOperationService.Stopped += OnGlobalOperationStopped; } } private void UnregisterGlobalOperationNotifications() { var globalOperationService = _services.GetService<IGlobalOperationNotificationService>(); if (globalOperationService != null) { globalOperationService.Started -= OnGlobalOperationStarted; globalOperationService.Stopped -= OnGlobalOperationStopped; } } private void OnGlobalOperationStarted(object? sender, EventArgs e) { lock (_globalNotificationsGate) { // Pass TaskContinuationOptions.OnlyOnRanToCompletion to avoid delivering further notifications once the task gets canceled or fails. // The cancellation happens only when VS is shutting down. The task might fail if communication with OOP fails. // Once that happens there is not point in sending more notifications to the remote service. _globalNotificationsTask = _globalNotificationsTask.SafeContinueWithFromAsync( SendStartNotificationAsync, _cancellationToken, TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.Default); } } private async Task<GlobalNotificationState> SendStartNotificationAsync(Task<GlobalNotificationState> previousTask) { // Can only transition from NotStarted->Started. If we hear about // anything else, do nothing. if (previousTask.Result != GlobalNotificationState.NotStarted) { return previousTask.Result; } var client = await RemoteHostClient.TryGetClientAsync(_services, _cancellationToken).ConfigureAwait(false); if (client == null) { return previousTask.Result; } _ = await client.TryInvokeAsync<IRemoteGlobalNotificationDeliveryService>( (service, cancellationToken) => service.OnGlobalOperationStartedAsync(cancellationToken), _cancellationToken).ConfigureAwait(false); return GlobalNotificationState.Started; } private void OnGlobalOperationStopped(object? sender, GlobalOperationEventArgs e) { lock (_globalNotificationsGate) { // Pass TaskContinuationOptions.OnlyOnRanToCompletion to avoid delivering further notifications once the task gets canceled or fails. // The cancellation happens only when VS is shutting down. The task might fail if communication with OOP fails. // Once that happens there is not point in sending more notifications to the remote service. _globalNotificationsTask = _globalNotificationsTask.SafeContinueWithFromAsync( previous => SendStoppedNotificationAsync(previous, e), _cancellationToken, TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.Default); } } private async Task<GlobalNotificationState> SendStoppedNotificationAsync(Task<GlobalNotificationState> previousTask, GlobalOperationEventArgs e) { // Can only transition from Started->NotStarted. If we hear about // anything else, do nothing. if (previousTask.Result != GlobalNotificationState.Started) { return previousTask.Result; } var client = await RemoteHostClient.TryGetClientAsync(_services, _cancellationToken).ConfigureAwait(false); if (client == null) { return previousTask.Result; } _ = await client.TryInvokeAsync<IRemoteGlobalNotificationDeliveryService>( (service, cancellationToken) => service.OnGlobalOperationStoppedAsync(e.Operations, cancellationToken), _cancellationToken).ConfigureAwait(false); // Mark that we're stopped now. return GlobalNotificationState.NotStarted; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Host; using Microsoft.CodeAnalysis.Notification; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Remote { /// <summary> /// Delivers global notifications to remote services. /// </summary> internal sealed class GlobalNotificationRemoteDeliveryService : IDisposable { private enum GlobalNotificationState { NotStarted, Started } /// <summary> /// Lock for the <see cref="_globalNotificationsTask"/> task chain. Each time we hear /// about a global operation starting or stopping (i.e. a build) we will '.ContinueWith' /// this task chain with a new notification to the OOP side. This way all the messages /// are properly serialized and appear in the right order (i.e. we don't hear about a /// stop prior to hearing about the relevant start). /// </summary> private readonly object _globalNotificationsGate = new object(); private Task<GlobalNotificationState> _globalNotificationsTask = Task.FromResult(GlobalNotificationState.NotStarted); private readonly HostWorkspaceServices _services; private readonly CancellationToken _cancellationToken; public GlobalNotificationRemoteDeliveryService(HostWorkspaceServices services, CancellationToken cancellationToken) { _services = services; _cancellationToken = cancellationToken; RegisterGlobalOperationNotifications(); } public void Dispose() { UnregisterGlobalOperationNotifications(); } private void RegisterGlobalOperationNotifications() { var globalOperationService = _services.GetService<IGlobalOperationNotificationService>(); if (globalOperationService != null) { globalOperationService.Started += OnGlobalOperationStarted; globalOperationService.Stopped += OnGlobalOperationStopped; } } private void UnregisterGlobalOperationNotifications() { var globalOperationService = _services.GetService<IGlobalOperationNotificationService>(); if (globalOperationService != null) { globalOperationService.Started -= OnGlobalOperationStarted; globalOperationService.Stopped -= OnGlobalOperationStopped; } } private void OnGlobalOperationStarted(object? sender, EventArgs e) { lock (_globalNotificationsGate) { // Pass TaskContinuationOptions.OnlyOnRanToCompletion to avoid delivering further notifications once the task gets canceled or fails. // The cancellation happens only when VS is shutting down. The task might fail if communication with OOP fails. // Once that happens there is not point in sending more notifications to the remote service. _globalNotificationsTask = _globalNotificationsTask.SafeContinueWithFromAsync( SendStartNotificationAsync, _cancellationToken, TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.Default); } } private async Task<GlobalNotificationState> SendStartNotificationAsync(Task<GlobalNotificationState> previousTask) { // Can only transition from NotStarted->Started. If we hear about // anything else, do nothing. if (previousTask.Result != GlobalNotificationState.NotStarted) { return previousTask.Result; } var client = await RemoteHostClient.TryGetClientAsync(_services, _cancellationToken).ConfigureAwait(false); if (client == null) { return previousTask.Result; } _ = await client.TryInvokeAsync<IRemoteGlobalNotificationDeliveryService>( (service, cancellationToken) => service.OnGlobalOperationStartedAsync(cancellationToken), _cancellationToken).ConfigureAwait(false); return GlobalNotificationState.Started; } private void OnGlobalOperationStopped(object? sender, GlobalOperationEventArgs e) { lock (_globalNotificationsGate) { // Pass TaskContinuationOptions.OnlyOnRanToCompletion to avoid delivering further notifications once the task gets canceled or fails. // The cancellation happens only when VS is shutting down. The task might fail if communication with OOP fails. // Once that happens there is not point in sending more notifications to the remote service. _globalNotificationsTask = _globalNotificationsTask.SafeContinueWithFromAsync( previous => SendStoppedNotificationAsync(previous, e), _cancellationToken, TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.Default); } } private async Task<GlobalNotificationState> SendStoppedNotificationAsync(Task<GlobalNotificationState> previousTask, GlobalOperationEventArgs e) { // Can only transition from Started->NotStarted. If we hear about // anything else, do nothing. if (previousTask.Result != GlobalNotificationState.Started) { return previousTask.Result; } var client = await RemoteHostClient.TryGetClientAsync(_services, _cancellationToken).ConfigureAwait(false); if (client == null) { return previousTask.Result; } _ = await client.TryInvokeAsync<IRemoteGlobalNotificationDeliveryService>( (service, cancellationToken) => service.OnGlobalOperationStoppedAsync(e.Operations, cancellationToken), _cancellationToken).ConfigureAwait(false); // Mark that we're stopped now. return GlobalNotificationState.NotStarted; } } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/EventSymbolReferenceFinder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.FindSymbols.Finders { internal class EventSymbolReferenceFinder : AbstractMethodOrPropertyOrEventSymbolReferenceFinder<IEventSymbol> { protected override bool CanFind(IEventSymbol symbol) => true; protected sealed override Task<ImmutableArray<ISymbol>> DetermineCascadedSymbolsAsync( IEventSymbol symbol, Solution solution, FindReferencesSearchOptions options, CancellationToken cancellationToken) { var backingFields = symbol.ContainingType.GetMembers() .OfType<IFieldSymbol>() .Where(f => symbol.Equals(f.AssociatedSymbol)) .ToImmutableArray<ISymbol>(); var associatedNamedTypes = symbol.ContainingType.GetTypeMembers() .WhereAsArray(n => symbol.Equals(n.AssociatedSymbol)) .CastArray<ISymbol>(); return Task.FromResult(backingFields.Concat(associatedNamedTypes)); } protected sealed override async Task<ImmutableArray<Document>> DetermineDocumentsToSearchAsync( IEventSymbol symbol, HashSet<string>? globalAliases, Project project, IImmutableSet<Document>? documents, FindReferencesSearchOptions options, CancellationToken cancellationToken) { var documentsWithName = await FindDocumentsAsync(project, documents, cancellationToken, symbol.Name).ConfigureAwait(false); var documentsWithGlobalAttributes = await FindDocumentsWithGlobalAttributesAsync(project, documents, cancellationToken).ConfigureAwait(false); return documentsWithName.Concat(documentsWithGlobalAttributes); } protected sealed override ValueTask<ImmutableArray<FinderLocation>> FindReferencesInDocumentAsync( IEventSymbol symbol, HashSet<string>? globalAliases, Document document, SemanticModel semanticModel, FindReferencesSearchOptions options, CancellationToken cancellationToken) { return FindReferencesInDocumentUsingSymbolNameAsync(symbol, document, semanticModel, cancellationToken); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.FindSymbols.Finders { internal class EventSymbolReferenceFinder : AbstractMethodOrPropertyOrEventSymbolReferenceFinder<IEventSymbol> { protected override bool CanFind(IEventSymbol symbol) => true; protected sealed override Task<ImmutableArray<ISymbol>> DetermineCascadedSymbolsAsync( IEventSymbol symbol, Solution solution, FindReferencesSearchOptions options, CancellationToken cancellationToken) { var backingFields = symbol.ContainingType.GetMembers() .OfType<IFieldSymbol>() .Where(f => symbol.Equals(f.AssociatedSymbol)) .ToImmutableArray<ISymbol>(); var associatedNamedTypes = symbol.ContainingType.GetTypeMembers() .WhereAsArray(n => symbol.Equals(n.AssociatedSymbol)) .CastArray<ISymbol>(); return Task.FromResult(backingFields.Concat(associatedNamedTypes)); } protected sealed override async Task<ImmutableArray<Document>> DetermineDocumentsToSearchAsync( IEventSymbol symbol, HashSet<string>? globalAliases, Project project, IImmutableSet<Document>? documents, FindReferencesSearchOptions options, CancellationToken cancellationToken) { var documentsWithName = await FindDocumentsAsync(project, documents, cancellationToken, symbol.Name).ConfigureAwait(false); var documentsWithGlobalAttributes = await FindDocumentsWithGlobalAttributesAsync(project, documents, cancellationToken).ConfigureAwait(false); return documentsWithName.Concat(documentsWithGlobalAttributes); } protected sealed override ValueTask<ImmutableArray<FinderLocation>> FindReferencesInDocumentAsync( IEventSymbol symbol, HashSet<string>? globalAliases, Document document, SemanticModel semanticModel, FindReferencesSearchOptions options, CancellationToken cancellationToken) { return FindReferencesInDocumentUsingSymbolNameAsync(symbol, document, semanticModel, cancellationToken); } } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/Compilers/CSharp/Portable/Symbols/Source/SourceNamespaceSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Threading; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal sealed partial class SourceNamespaceSymbol : NamespaceSymbol { private readonly SourceModuleSymbol _module; private readonly Symbol _container; private readonly MergedNamespaceDeclaration _mergedDeclaration; private SymbolCompletionState _state; private ImmutableArray<Location> _locations; private Dictionary<string, ImmutableArray<NamespaceOrTypeSymbol>> _nameToMembersMap; private Dictionary<string, ImmutableArray<NamedTypeSymbol>> _nameToTypeMembersMap; private ImmutableArray<Symbol> _lazyAllMembers; private ImmutableArray<NamedTypeSymbol> _lazyTypeMembersUnordered; private readonly ImmutableSegmentedDictionary<SingleNamespaceDeclaration, AliasesAndUsings> _aliasesAndUsings; #if DEBUG private readonly ImmutableSegmentedDictionary<SingleNamespaceDeclaration, AliasesAndUsings> _aliasesAndUsingsForAsserts; #endif private MergedGlobalAliasesAndUsings _lazyMergedGlobalAliasesAndUsings; private const int LazyAllMembersIsSorted = 0x1; // Set if "lazyAllMembers" is sorted. private int _flags; private LexicalSortKey _lazyLexicalSortKey = LexicalSortKey.NotInitialized; internal SourceNamespaceSymbol( SourceModuleSymbol module, Symbol container, MergedNamespaceDeclaration mergedDeclaration, BindingDiagnosticBag diagnostics) { Debug.Assert(mergedDeclaration != null); _module = module; _container = container; _mergedDeclaration = mergedDeclaration; var builder = ImmutableSegmentedDictionary.CreateBuilder<SingleNamespaceDeclaration, AliasesAndUsings>(ReferenceEqualityComparer.Instance); #if DEBUG var builderForAsserts = ImmutableSegmentedDictionary.CreateBuilder<SingleNamespaceDeclaration, AliasesAndUsings>(ReferenceEqualityComparer.Instance); #endif foreach (var singleDeclaration in mergedDeclaration.Declarations) { if (singleDeclaration.HasExternAliases || singleDeclaration.HasGlobalUsings || singleDeclaration.HasUsings) { builder.Add(singleDeclaration, new AliasesAndUsings()); } #if DEBUG else { builderForAsserts.Add(singleDeclaration, new AliasesAndUsings()); } #endif diagnostics.AddRange(singleDeclaration.Diagnostics); } _aliasesAndUsings = builder.ToImmutable(); #if DEBUG _aliasesAndUsingsForAsserts = builderForAsserts.ToImmutable(); #endif } internal MergedNamespaceDeclaration MergedDeclaration => _mergedDeclaration; public override Symbol ContainingSymbol => _container; public override AssemblySymbol ContainingAssembly => _module.ContainingAssembly; public override string Name => _mergedDeclaration.Name; internal override LexicalSortKey GetLexicalSortKey() { if (!_lazyLexicalSortKey.IsInitialized) { _lazyLexicalSortKey.SetFrom(_mergedDeclaration.GetLexicalSortKey(this.DeclaringCompilation)); } return _lazyLexicalSortKey; } public override ImmutableArray<Location> Locations { get { if (_locations.IsDefault) { ImmutableInterlocked.InterlockedCompareExchange(ref _locations, _mergedDeclaration.NameLocations, default); } return _locations; } } private static readonly Func<SingleNamespaceDeclaration, SyntaxReference> s_declaringSyntaxReferencesSelector = d => new NamespaceDeclarationSyntaxReference(d.SyntaxReference); public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences => ComputeDeclaringReferencesCore(); private ImmutableArray<SyntaxReference> ComputeDeclaringReferencesCore() { // SyntaxReference in the namespace declaration points to the name node of the namespace decl node not // namespace decl node we want to return. here we will wrap the original syntax reference in // the translation syntax reference so that we can lazily manipulate a node return to the caller return _mergedDeclaration.Declarations.SelectAsArray(s_declaringSyntaxReferencesSelector); } internal override ImmutableArray<Symbol> GetMembersUnordered() { var result = _lazyAllMembers; if (result.IsDefault) { var members = StaticCast<Symbol>.From(this.GetNameToMembersMap().Flatten(null)); // don't sort. ImmutableInterlocked.InterlockedInitialize(ref _lazyAllMembers, members); result = _lazyAllMembers; } return result.ConditionallyDeOrder(); } public override ImmutableArray<Symbol> GetMembers() { if ((_flags & LazyAllMembersIsSorted) != 0) { return _lazyAllMembers; } else { var allMembers = this.GetMembersUnordered(); if (allMembers.Length >= 2) { // The array isn't sorted. Sort it and remember that we sorted it. allMembers = allMembers.Sort(LexicalOrderSymbolComparer.Instance); ImmutableInterlocked.InterlockedExchange(ref _lazyAllMembers, allMembers); } ThreadSafeFlagOperations.Set(ref _flags, LazyAllMembersIsSorted); return allMembers; } } public override ImmutableArray<Symbol> GetMembers(string name) { ImmutableArray<NamespaceOrTypeSymbol> members; return this.GetNameToMembersMap().TryGetValue(name, out members) ? members.Cast<NamespaceOrTypeSymbol, Symbol>() : ImmutableArray<Symbol>.Empty; } internal override ImmutableArray<NamedTypeSymbol> GetTypeMembersUnordered() { if (_lazyTypeMembersUnordered.IsDefault) { var members = this.GetNameToTypeMembersMap().Flatten(); ImmutableInterlocked.InterlockedInitialize(ref _lazyTypeMembersUnordered, members); } return _lazyTypeMembersUnordered; } public override ImmutableArray<NamedTypeSymbol> GetTypeMembers() { return this.GetNameToTypeMembersMap().Flatten(LexicalOrderSymbolComparer.Instance); } public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name) { ImmutableArray<NamedTypeSymbol> members; return this.GetNameToTypeMembersMap().TryGetValue(name, out members) ? members : ImmutableArray<NamedTypeSymbol>.Empty; } public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name, int arity) { return GetTypeMembers(name).WhereAsArray((s, arity) => s.Arity == arity, arity); } internal override ModuleSymbol ContainingModule { get { return _module; } } internal override NamespaceExtent Extent { get { return new NamespaceExtent(_module); } } private Dictionary<string, ImmutableArray<NamespaceOrTypeSymbol>> GetNameToMembersMap() { if (_nameToMembersMap == null) { var diagnostics = BindingDiagnosticBag.GetInstance(); if (Interlocked.CompareExchange(ref _nameToMembersMap, MakeNameToMembersMap(diagnostics), null) == null) { // NOTE: the following is not cancellable. Once we've set the // members, we *must* do the following to make sure we're in a consistent state. this.AddDeclarationDiagnostics(diagnostics); RegisterDeclaredCorTypes(); // We may produce a SymbolDeclaredEvent for the enclosing namespace before events for its contained members DeclaringCompilation.SymbolDeclaredEvent(this); var wasSetThisThread = _state.NotePartComplete(CompletionPart.NameToMembersMap); Debug.Assert(wasSetThisThread); } diagnostics.Free(); } return _nameToMembersMap; } private Dictionary<string, ImmutableArray<NamedTypeSymbol>> GetNameToTypeMembersMap() { if (_nameToTypeMembersMap == null) { // NOTE: This method depends on MakeNameToMembersMap() on creating a proper // NOTE: type of the array, see comments in MakeNameToMembersMap() for details Interlocked.CompareExchange(ref _nameToTypeMembersMap, GetTypesFromMemberMap(GetNameToMembersMap()), null); } return _nameToTypeMembersMap; } private static Dictionary<string, ImmutableArray<NamedTypeSymbol>> GetTypesFromMemberMap(Dictionary<string, ImmutableArray<NamespaceOrTypeSymbol>> map) { var dictionary = new Dictionary<string, ImmutableArray<NamedTypeSymbol>>(StringOrdinalComparer.Instance); foreach (var kvp in map) { ImmutableArray<NamespaceOrTypeSymbol> members = kvp.Value; bool hasType = false; bool hasNamespace = false; foreach (var symbol in members) { if (symbol.Kind == SymbolKind.NamedType) { hasType = true; if (hasNamespace) { break; } } else { Debug.Assert(symbol.Kind == SymbolKind.Namespace); hasNamespace = true; if (hasType) { break; } } } if (hasType) { if (hasNamespace) { dictionary.Add(kvp.Key, members.OfType<NamedTypeSymbol>().AsImmutable()); } else { dictionary.Add(kvp.Key, members.As<NamedTypeSymbol>()); } } } return dictionary; } private Dictionary<string, ImmutableArray<NamespaceOrTypeSymbol>> MakeNameToMembersMap(BindingDiagnosticBag diagnostics) { // NOTE: Even though the resulting map stores ImmutableArray<NamespaceOrTypeSymbol> as // NOTE: values if the name is mapped into an array of named types, which is frequently // NOTE: the case, we actually create an array of NamedTypeSymbol[] and wrap it in // NOTE: ImmutableArray<NamespaceOrTypeSymbol> // NOTE: // NOTE: This way we can save time and memory in GetNameToTypeMembersMap() -- when we see that // NOTE: a name maps into values collection containing types only instead of allocating another // NOTE: array of NamedTypeSymbol[] we downcast the array to ImmutableArray<NamedTypeSymbol> var builder = new NameToSymbolMapBuilder(_mergedDeclaration.Children.Length); foreach (var declaration in _mergedDeclaration.Children) { builder.Add(BuildSymbol(declaration, diagnostics)); } var result = builder.CreateMap(); CheckMembers(this, result, diagnostics); return result; } private static void CheckMembers(NamespaceSymbol @namespace, Dictionary<string, ImmutableArray<NamespaceOrTypeSymbol>> result, BindingDiagnosticBag diagnostics) { var memberOfArity = new Symbol[10]; MergedNamespaceSymbol mergedAssemblyNamespace = null; if (@namespace.ContainingAssembly.Modules.Length > 1) { mergedAssemblyNamespace = @namespace.ContainingAssembly.GetAssemblyNamespace(@namespace) as MergedNamespaceSymbol; } foreach (var name in result.Keys) { Array.Clear(memberOfArity, 0, memberOfArity.Length); foreach (var symbol in result[name]) { var nts = symbol as NamedTypeSymbol; var arity = ((object)nts != null) ? nts.Arity : 0; if (arity >= memberOfArity.Length) { Array.Resize(ref memberOfArity, arity + 1); } var other = memberOfArity[arity]; if ((object)other == null && (object)mergedAssemblyNamespace != null) { // Check for collision with declarations from added modules. foreach (NamespaceSymbol constituent in mergedAssemblyNamespace.ConstituentNamespaces) { if ((object)constituent != (object)@namespace) { // For whatever reason native compiler only detects conflicts against types. // It doesn't complain when source declares a type with the same name as // a namespace in added module, but complains when source declares a namespace // with the same name as a type in added module. var types = constituent.GetTypeMembers(symbol.Name, arity); if (types.Length > 0) { other = types[0]; // Since the error doesn't specify what added module this type belongs to, we can stop searching // at the first match. break; } } } } if ((object)other != null) { if ((nts as SourceNamedTypeSymbol)?.IsPartial == true && (other as SourceNamedTypeSymbol)?.IsPartial == true) { diagnostics.Add(ErrorCode.ERR_PartialTypeKindConflict, symbol.Locations.FirstOrNone(), symbol); } else { diagnostics.Add(ErrorCode.ERR_DuplicateNameInNS, symbol.Locations.FirstOrNone(), name, @namespace); } } memberOfArity[arity] = symbol; if ((object)nts != null) { //types declared at the namespace level may only have declared accessibility of public or internal (Section 3.5.1) Accessibility declaredAccessibility = nts.DeclaredAccessibility; if (declaredAccessibility != Accessibility.Public && declaredAccessibility != Accessibility.Internal) { diagnostics.Add(ErrorCode.ERR_NoNamespacePrivate, symbol.Locations.FirstOrNone()); } } } } } private NamespaceOrTypeSymbol BuildSymbol(MergedNamespaceOrTypeDeclaration declaration, BindingDiagnosticBag diagnostics) { switch (declaration.Kind) { case DeclarationKind.Namespace: return new SourceNamespaceSymbol(_module, this, (MergedNamespaceDeclaration)declaration, diagnostics); case DeclarationKind.Struct: case DeclarationKind.Interface: case DeclarationKind.Enum: case DeclarationKind.Delegate: case DeclarationKind.Class: case DeclarationKind.Record: case DeclarationKind.RecordStruct: return new SourceNamedTypeSymbol(this, (MergedTypeDeclaration)declaration, diagnostics); case DeclarationKind.Script: case DeclarationKind.Submission: case DeclarationKind.ImplicitClass: return new ImplicitNamedTypeSymbol(this, (MergedTypeDeclaration)declaration, diagnostics); default: throw ExceptionUtilities.UnexpectedValue(declaration.Kind); } } /// <summary> /// Register COR types declared in this namespace, if any, in the COR types cache. /// </summary> private void RegisterDeclaredCorTypes() { AssemblySymbol containingAssembly = ContainingAssembly; if (containingAssembly.KeepLookingForDeclaredSpecialTypes) { // Register newly declared COR types foreach (var array in _nameToMembersMap.Values) { foreach (var member in array) { var type = member as NamedTypeSymbol; if ((object)type != null && type.SpecialType != SpecialType.None) { containingAssembly.RegisterDeclaredSpecialType(type); if (!containingAssembly.KeepLookingForDeclaredSpecialTypes) { return; } } } } } } internal override bool IsDefinedInSourceTree(SyntaxTree tree, TextSpan? definedWithinSpan, CancellationToken cancellationToken = default(CancellationToken)) { if (this.IsGlobalNamespace) { return true; } // Check if any namespace declaration block intersects with the given tree/span. foreach (var declaration in _mergedDeclaration.Declarations) { cancellationToken.ThrowIfCancellationRequested(); var declarationSyntaxRef = declaration.SyntaxReference; if (declarationSyntaxRef.SyntaxTree != tree) { continue; } if (!definedWithinSpan.HasValue) { return true; } var syntax = NamespaceDeclarationSyntaxReference.GetSyntax(declarationSyntaxRef, cancellationToken); if (syntax.FullSpan.IntersectsWith(definedWithinSpan.Value)) { return true; } } return false; } private struct NameToSymbolMapBuilder { private readonly Dictionary<string, object> _dictionary; public NameToSymbolMapBuilder(int capacity) { _dictionary = new Dictionary<string, object>(capacity, StringOrdinalComparer.Instance); } public void Add(NamespaceOrTypeSymbol symbol) { string name = symbol.Name; object item; if (_dictionary.TryGetValue(name, out item)) { var builder = item as ArrayBuilder<NamespaceOrTypeSymbol>; if (builder == null) { builder = ArrayBuilder<NamespaceOrTypeSymbol>.GetInstance(); builder.Add((NamespaceOrTypeSymbol)item); _dictionary[name] = builder; } builder.Add(symbol); } else { _dictionary[name] = symbol; } } public Dictionary<String, ImmutableArray<NamespaceOrTypeSymbol>> CreateMap() { var result = new Dictionary<String, ImmutableArray<NamespaceOrTypeSymbol>>(_dictionary.Count, StringOrdinalComparer.Instance); foreach (var kvp in _dictionary) { object value = kvp.Value; ImmutableArray<NamespaceOrTypeSymbol> members; var builder = value as ArrayBuilder<NamespaceOrTypeSymbol>; if (builder != null) { Debug.Assert(builder.Count > 1); bool hasNamespaces = false; for (int i = 0; (i < builder.Count) && !hasNamespaces; i++) { hasNamespaces |= (builder[i].Kind == SymbolKind.Namespace); } members = hasNamespaces ? builder.ToImmutable() : StaticCast<NamespaceOrTypeSymbol>.From(builder.ToDowncastedImmutable<NamedTypeSymbol>()); builder.Free(); } else { NamespaceOrTypeSymbol symbol = (NamespaceOrTypeSymbol)value; members = symbol.Kind == SymbolKind.Namespace ? ImmutableArray.Create<NamespaceOrTypeSymbol>(symbol) : StaticCast<NamespaceOrTypeSymbol>.From(ImmutableArray.Create<NamedTypeSymbol>((NamedTypeSymbol)symbol)); } result.Add(kvp.Key, members); } return result; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal sealed partial class SourceNamespaceSymbol : NamespaceSymbol { private readonly SourceModuleSymbol _module; private readonly Symbol _container; private readonly MergedNamespaceDeclaration _mergedDeclaration; private SymbolCompletionState _state; private ImmutableArray<Location> _locations; private Dictionary<string, ImmutableArray<NamespaceOrTypeSymbol>> _nameToMembersMap; private Dictionary<string, ImmutableArray<NamedTypeSymbol>> _nameToTypeMembersMap; private ImmutableArray<Symbol> _lazyAllMembers; private ImmutableArray<NamedTypeSymbol> _lazyTypeMembersUnordered; private readonly ImmutableSegmentedDictionary<SingleNamespaceDeclaration, AliasesAndUsings> _aliasesAndUsings; #if DEBUG private readonly ImmutableSegmentedDictionary<SingleNamespaceDeclaration, AliasesAndUsings> _aliasesAndUsingsForAsserts; #endif private MergedGlobalAliasesAndUsings _lazyMergedGlobalAliasesAndUsings; private const int LazyAllMembersIsSorted = 0x1; // Set if "lazyAllMembers" is sorted. private int _flags; private LexicalSortKey _lazyLexicalSortKey = LexicalSortKey.NotInitialized; internal SourceNamespaceSymbol( SourceModuleSymbol module, Symbol container, MergedNamespaceDeclaration mergedDeclaration, BindingDiagnosticBag diagnostics) { Debug.Assert(mergedDeclaration != null); _module = module; _container = container; _mergedDeclaration = mergedDeclaration; var builder = ImmutableSegmentedDictionary.CreateBuilder<SingleNamespaceDeclaration, AliasesAndUsings>(ReferenceEqualityComparer.Instance); #if DEBUG var builderForAsserts = ImmutableSegmentedDictionary.CreateBuilder<SingleNamespaceDeclaration, AliasesAndUsings>(ReferenceEqualityComparer.Instance); #endif foreach (var singleDeclaration in mergedDeclaration.Declarations) { if (singleDeclaration.HasExternAliases || singleDeclaration.HasGlobalUsings || singleDeclaration.HasUsings) { builder.Add(singleDeclaration, new AliasesAndUsings()); } #if DEBUG else { builderForAsserts.Add(singleDeclaration, new AliasesAndUsings()); } #endif diagnostics.AddRange(singleDeclaration.Diagnostics); } _aliasesAndUsings = builder.ToImmutable(); #if DEBUG _aliasesAndUsingsForAsserts = builderForAsserts.ToImmutable(); #endif } internal MergedNamespaceDeclaration MergedDeclaration => _mergedDeclaration; public override Symbol ContainingSymbol => _container; public override AssemblySymbol ContainingAssembly => _module.ContainingAssembly; public override string Name => _mergedDeclaration.Name; internal override LexicalSortKey GetLexicalSortKey() { if (!_lazyLexicalSortKey.IsInitialized) { _lazyLexicalSortKey.SetFrom(_mergedDeclaration.GetLexicalSortKey(this.DeclaringCompilation)); } return _lazyLexicalSortKey; } public override ImmutableArray<Location> Locations { get { if (_locations.IsDefault) { ImmutableInterlocked.InterlockedCompareExchange(ref _locations, _mergedDeclaration.NameLocations, default); } return _locations; } } private static readonly Func<SingleNamespaceDeclaration, SyntaxReference> s_declaringSyntaxReferencesSelector = d => new NamespaceDeclarationSyntaxReference(d.SyntaxReference); public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences => ComputeDeclaringReferencesCore(); private ImmutableArray<SyntaxReference> ComputeDeclaringReferencesCore() { // SyntaxReference in the namespace declaration points to the name node of the namespace decl node not // namespace decl node we want to return. here we will wrap the original syntax reference in // the translation syntax reference so that we can lazily manipulate a node return to the caller return _mergedDeclaration.Declarations.SelectAsArray(s_declaringSyntaxReferencesSelector); } internal override ImmutableArray<Symbol> GetMembersUnordered() { var result = _lazyAllMembers; if (result.IsDefault) { var members = StaticCast<Symbol>.From(this.GetNameToMembersMap().Flatten(null)); // don't sort. ImmutableInterlocked.InterlockedInitialize(ref _lazyAllMembers, members); result = _lazyAllMembers; } return result.ConditionallyDeOrder(); } public override ImmutableArray<Symbol> GetMembers() { if ((_flags & LazyAllMembersIsSorted) != 0) { return _lazyAllMembers; } else { var allMembers = this.GetMembersUnordered(); if (allMembers.Length >= 2) { // The array isn't sorted. Sort it and remember that we sorted it. allMembers = allMembers.Sort(LexicalOrderSymbolComparer.Instance); ImmutableInterlocked.InterlockedExchange(ref _lazyAllMembers, allMembers); } ThreadSafeFlagOperations.Set(ref _flags, LazyAllMembersIsSorted); return allMembers; } } public override ImmutableArray<Symbol> GetMembers(string name) { ImmutableArray<NamespaceOrTypeSymbol> members; return this.GetNameToMembersMap().TryGetValue(name, out members) ? members.Cast<NamespaceOrTypeSymbol, Symbol>() : ImmutableArray<Symbol>.Empty; } internal override ImmutableArray<NamedTypeSymbol> GetTypeMembersUnordered() { if (_lazyTypeMembersUnordered.IsDefault) { var members = this.GetNameToTypeMembersMap().Flatten(); ImmutableInterlocked.InterlockedInitialize(ref _lazyTypeMembersUnordered, members); } return _lazyTypeMembersUnordered; } public override ImmutableArray<NamedTypeSymbol> GetTypeMembers() { return this.GetNameToTypeMembersMap().Flatten(LexicalOrderSymbolComparer.Instance); } public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name) { ImmutableArray<NamedTypeSymbol> members; return this.GetNameToTypeMembersMap().TryGetValue(name, out members) ? members : ImmutableArray<NamedTypeSymbol>.Empty; } public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name, int arity) { return GetTypeMembers(name).WhereAsArray((s, arity) => s.Arity == arity, arity); } internal override ModuleSymbol ContainingModule { get { return _module; } } internal override NamespaceExtent Extent { get { return new NamespaceExtent(_module); } } private Dictionary<string, ImmutableArray<NamespaceOrTypeSymbol>> GetNameToMembersMap() { if (_nameToMembersMap == null) { var diagnostics = BindingDiagnosticBag.GetInstance(); if (Interlocked.CompareExchange(ref _nameToMembersMap, MakeNameToMembersMap(diagnostics), null) == null) { // NOTE: the following is not cancellable. Once we've set the // members, we *must* do the following to make sure we're in a consistent state. this.AddDeclarationDiagnostics(diagnostics); RegisterDeclaredCorTypes(); // We may produce a SymbolDeclaredEvent for the enclosing namespace before events for its contained members DeclaringCompilation.SymbolDeclaredEvent(this); var wasSetThisThread = _state.NotePartComplete(CompletionPart.NameToMembersMap); Debug.Assert(wasSetThisThread); } diagnostics.Free(); } return _nameToMembersMap; } private Dictionary<string, ImmutableArray<NamedTypeSymbol>> GetNameToTypeMembersMap() { if (_nameToTypeMembersMap == null) { // NOTE: This method depends on MakeNameToMembersMap() on creating a proper // NOTE: type of the array, see comments in MakeNameToMembersMap() for details Interlocked.CompareExchange(ref _nameToTypeMembersMap, GetTypesFromMemberMap(GetNameToMembersMap()), null); } return _nameToTypeMembersMap; } private static Dictionary<string, ImmutableArray<NamedTypeSymbol>> GetTypesFromMemberMap(Dictionary<string, ImmutableArray<NamespaceOrTypeSymbol>> map) { var dictionary = new Dictionary<string, ImmutableArray<NamedTypeSymbol>>(StringOrdinalComparer.Instance); foreach (var kvp in map) { ImmutableArray<NamespaceOrTypeSymbol> members = kvp.Value; bool hasType = false; bool hasNamespace = false; foreach (var symbol in members) { if (symbol.Kind == SymbolKind.NamedType) { hasType = true; if (hasNamespace) { break; } } else { Debug.Assert(symbol.Kind == SymbolKind.Namespace); hasNamespace = true; if (hasType) { break; } } } if (hasType) { if (hasNamespace) { dictionary.Add(kvp.Key, members.OfType<NamedTypeSymbol>().AsImmutable()); } else { dictionary.Add(kvp.Key, members.As<NamedTypeSymbol>()); } } } return dictionary; } private Dictionary<string, ImmutableArray<NamespaceOrTypeSymbol>> MakeNameToMembersMap(BindingDiagnosticBag diagnostics) { // NOTE: Even though the resulting map stores ImmutableArray<NamespaceOrTypeSymbol> as // NOTE: values if the name is mapped into an array of named types, which is frequently // NOTE: the case, we actually create an array of NamedTypeSymbol[] and wrap it in // NOTE: ImmutableArray<NamespaceOrTypeSymbol> // NOTE: // NOTE: This way we can save time and memory in GetNameToTypeMembersMap() -- when we see that // NOTE: a name maps into values collection containing types only instead of allocating another // NOTE: array of NamedTypeSymbol[] we downcast the array to ImmutableArray<NamedTypeSymbol> var builder = new NameToSymbolMapBuilder(_mergedDeclaration.Children.Length); foreach (var declaration in _mergedDeclaration.Children) { builder.Add(BuildSymbol(declaration, diagnostics)); } var result = builder.CreateMap(); CheckMembers(this, result, diagnostics); return result; } private static void CheckMembers(NamespaceSymbol @namespace, Dictionary<string, ImmutableArray<NamespaceOrTypeSymbol>> result, BindingDiagnosticBag diagnostics) { var memberOfArity = new Symbol[10]; MergedNamespaceSymbol mergedAssemblyNamespace = null; if (@namespace.ContainingAssembly.Modules.Length > 1) { mergedAssemblyNamespace = @namespace.ContainingAssembly.GetAssemblyNamespace(@namespace) as MergedNamespaceSymbol; } foreach (var name in result.Keys) { Array.Clear(memberOfArity, 0, memberOfArity.Length); foreach (var symbol in result[name]) { var nts = symbol as NamedTypeSymbol; var arity = ((object)nts != null) ? nts.Arity : 0; if (arity >= memberOfArity.Length) { Array.Resize(ref memberOfArity, arity + 1); } var other = memberOfArity[arity]; if ((object)other == null && (object)mergedAssemblyNamespace != null) { // Check for collision with declarations from added modules. foreach (NamespaceSymbol constituent in mergedAssemblyNamespace.ConstituentNamespaces) { if ((object)constituent != (object)@namespace) { // For whatever reason native compiler only detects conflicts against types. // It doesn't complain when source declares a type with the same name as // a namespace in added module, but complains when source declares a namespace // with the same name as a type in added module. var types = constituent.GetTypeMembers(symbol.Name, arity); if (types.Length > 0) { other = types[0]; // Since the error doesn't specify what added module this type belongs to, we can stop searching // at the first match. break; } } } } if ((object)other != null) { if ((nts as SourceNamedTypeSymbol)?.IsPartial == true && (other as SourceNamedTypeSymbol)?.IsPartial == true) { diagnostics.Add(ErrorCode.ERR_PartialTypeKindConflict, symbol.Locations.FirstOrNone(), symbol); } else { diagnostics.Add(ErrorCode.ERR_DuplicateNameInNS, symbol.Locations.FirstOrNone(), name, @namespace); } } memberOfArity[arity] = symbol; if ((object)nts != null) { //types declared at the namespace level may only have declared accessibility of public or internal (Section 3.5.1) Accessibility declaredAccessibility = nts.DeclaredAccessibility; if (declaredAccessibility != Accessibility.Public && declaredAccessibility != Accessibility.Internal) { diagnostics.Add(ErrorCode.ERR_NoNamespacePrivate, symbol.Locations.FirstOrNone()); } } } } } private NamespaceOrTypeSymbol BuildSymbol(MergedNamespaceOrTypeDeclaration declaration, BindingDiagnosticBag diagnostics) { switch (declaration.Kind) { case DeclarationKind.Namespace: return new SourceNamespaceSymbol(_module, this, (MergedNamespaceDeclaration)declaration, diagnostics); case DeclarationKind.Struct: case DeclarationKind.Interface: case DeclarationKind.Enum: case DeclarationKind.Delegate: case DeclarationKind.Class: case DeclarationKind.Record: case DeclarationKind.RecordStruct: return new SourceNamedTypeSymbol(this, (MergedTypeDeclaration)declaration, diagnostics); case DeclarationKind.Script: case DeclarationKind.Submission: case DeclarationKind.ImplicitClass: return new ImplicitNamedTypeSymbol(this, (MergedTypeDeclaration)declaration, diagnostics); default: throw ExceptionUtilities.UnexpectedValue(declaration.Kind); } } /// <summary> /// Register COR types declared in this namespace, if any, in the COR types cache. /// </summary> private void RegisterDeclaredCorTypes() { AssemblySymbol containingAssembly = ContainingAssembly; if (containingAssembly.KeepLookingForDeclaredSpecialTypes) { // Register newly declared COR types foreach (var array in _nameToMembersMap.Values) { foreach (var member in array) { var type = member as NamedTypeSymbol; if ((object)type != null && type.SpecialType != SpecialType.None) { containingAssembly.RegisterDeclaredSpecialType(type); if (!containingAssembly.KeepLookingForDeclaredSpecialTypes) { return; } } } } } } internal override bool IsDefinedInSourceTree(SyntaxTree tree, TextSpan? definedWithinSpan, CancellationToken cancellationToken = default(CancellationToken)) { if (this.IsGlobalNamespace) { return true; } // Check if any namespace declaration block intersects with the given tree/span. foreach (var declaration in _mergedDeclaration.Declarations) { cancellationToken.ThrowIfCancellationRequested(); var declarationSyntaxRef = declaration.SyntaxReference; if (declarationSyntaxRef.SyntaxTree != tree) { continue; } if (!definedWithinSpan.HasValue) { return true; } var syntax = NamespaceDeclarationSyntaxReference.GetSyntax(declarationSyntaxRef, cancellationToken); if (syntax.FullSpan.IntersectsWith(definedWithinSpan.Value)) { return true; } } return false; } private struct NameToSymbolMapBuilder { private readonly Dictionary<string, object> _dictionary; public NameToSymbolMapBuilder(int capacity) { _dictionary = new Dictionary<string, object>(capacity, StringOrdinalComparer.Instance); } public void Add(NamespaceOrTypeSymbol symbol) { string name = symbol.Name; object item; if (_dictionary.TryGetValue(name, out item)) { var builder = item as ArrayBuilder<NamespaceOrTypeSymbol>; if (builder == null) { builder = ArrayBuilder<NamespaceOrTypeSymbol>.GetInstance(); builder.Add((NamespaceOrTypeSymbol)item); _dictionary[name] = builder; } builder.Add(symbol); } else { _dictionary[name] = symbol; } } public Dictionary<String, ImmutableArray<NamespaceOrTypeSymbol>> CreateMap() { var result = new Dictionary<String, ImmutableArray<NamespaceOrTypeSymbol>>(_dictionary.Count, StringOrdinalComparer.Instance); foreach (var kvp in _dictionary) { object value = kvp.Value; ImmutableArray<NamespaceOrTypeSymbol> members; var builder = value as ArrayBuilder<NamespaceOrTypeSymbol>; if (builder != null) { Debug.Assert(builder.Count > 1); bool hasNamespaces = false; for (int i = 0; (i < builder.Count) && !hasNamespaces; i++) { hasNamespaces |= (builder[i].Kind == SymbolKind.Namespace); } members = hasNamespaces ? builder.ToImmutable() : StaticCast<NamespaceOrTypeSymbol>.From(builder.ToDowncastedImmutable<NamedTypeSymbol>()); builder.Free(); } else { NamespaceOrTypeSymbol symbol = (NamespaceOrTypeSymbol)value; members = symbol.Kind == SymbolKind.Namespace ? ImmutableArray.Create<NamespaceOrTypeSymbol>(symbol) : StaticCast<NamespaceOrTypeSymbol>.From(ImmutableArray.Create<NamedTypeSymbol>((NamedTypeSymbol)symbol)); } result.Add(kvp.Key, members); } return result; } } } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/EditorFeatures/CSharp/GoToDefinition/CSharpGoToSymbolService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Editor.GoToDefinition; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.Editor.CSharp.GoToDefinition { [ExportLanguageService(typeof(IGoToSymbolService), LanguageNames.CSharp), Shared] internal class CSharpGoToSymbolService : AbstractGoToSymbolService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpGoToSymbolService(IThreadingContext threadingContext) : base(threadingContext) { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Editor.GoToDefinition; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.Editor.CSharp.GoToDefinition { [ExportLanguageService(typeof(IGoToSymbolService), LanguageNames.CSharp), Shared] internal class CSharpGoToSymbolService : AbstractGoToSymbolService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpGoToSymbolService(IThreadingContext threadingContext) : base(threadingContext) { } } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/Workspaces/Core/Portable/Editing/SyntaxEditor.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editing { /// <summary> /// An editor for making changes to a syntax tree. /// </summary> public class SyntaxEditor { private readonly SyntaxGenerator _generator; private readonly List<Change> _changes; private bool _allowEditsOnLazilyCreatedTrackedNewNodes; private HashSet<SyntaxNode>? _lazyTrackedNewNodesOpt; /// <summary> /// Creates a new <see cref="SyntaxEditor"/> instance. /// </summary> public SyntaxEditor(SyntaxNode root, Workspace workspace) { if (workspace == null) { throw new ArgumentNullException(nameof(workspace)); } OriginalRoot = root ?? throw new ArgumentNullException(nameof(root)); _generator = SyntaxGenerator.GetGenerator(workspace, root.Language); _changes = new List<Change>(); } internal SyntaxEditor(SyntaxNode root, SyntaxGenerator generator) { OriginalRoot = root ?? throw new ArgumentNullException(nameof(root)); _generator = generator; _changes = new List<Change>(); } [return: NotNullIfNotNull("node")] private SyntaxNode? ApplyTrackingToNewNode(SyntaxNode? node) { if (node == null) { return null; } _lazyTrackedNewNodesOpt ??= new HashSet<SyntaxNode>(); foreach (var descendant in node.DescendantNodesAndSelf()) { _lazyTrackedNewNodesOpt.Add(descendant); } return node.TrackNodes(node.DescendantNodesAndSelf()); } private IEnumerable<SyntaxNode> ApplyTrackingToNewNodes(IEnumerable<SyntaxNode> nodes) { foreach (var node in nodes) { var result = ApplyTrackingToNewNode(node); yield return result; } } /// <summary> /// The <see cref="SyntaxNode"/> that was specified when the <see cref="SyntaxEditor"/> was constructed. /// </summary> public SyntaxNode OriginalRoot { get; } /// <summary> /// A <see cref="SyntaxGenerator"/> to use to create and change <see cref="SyntaxNode"/>'s. /// </summary> public SyntaxGenerator Generator => _generator; /// <summary> /// Returns the changed root node. /// </summary> public SyntaxNode GetChangedRoot() { var nodes = Enumerable.Distinct(_changes.Where(c => OriginalRoot.Contains(c.Node)) .Select(c => c.Node)); var newRoot = OriginalRoot.TrackNodes(nodes); foreach (var change in _changes) { newRoot = change.Apply(newRoot, _generator); } return newRoot; } /// <summary> /// Makes sure the node is tracked, even if it is not changed. /// </summary> public void TrackNode(SyntaxNode node) { CheckNodeInOriginalTreeOrTracked(node); _changes.Add(new NoChange(node)); } /// <summary> /// Remove the node from the tree. /// </summary> /// <param name="node">The node to remove that currently exists as part of the tree.</param> public void RemoveNode(SyntaxNode node) => RemoveNode(node, SyntaxGenerator.DefaultRemoveOptions); /// <summary> /// Remove the node from the tree. /// </summary> /// <param name="node">The node to remove that currently exists as part of the tree.</param> /// <param name="options">Options that affect how node removal works.</param> public void RemoveNode(SyntaxNode node, SyntaxRemoveOptions options) { CheckNodeInOriginalTreeOrTracked(node); _changes.Add(new RemoveChange(node, options)); } /// <summary> /// Replace the specified node with a node produced by the function. /// </summary> /// <param name="node">The node to replace that already exists in the tree.</param> /// <param name="computeReplacement">A function that computes a replacement node. /// The node passed into the compute function includes changes from prior edits. It will not appear as a descendant of the original root.</param> public void ReplaceNode(SyntaxNode node, Func<SyntaxNode, SyntaxGenerator, SyntaxNode> computeReplacement) { CheckNodeInOriginalTreeOrTracked(node); if (computeReplacement == null) { throw new ArgumentNullException(nameof(computeReplacement)); } _allowEditsOnLazilyCreatedTrackedNewNodes = true; _changes.Add(new ReplaceChange(node, computeReplacement, this)); } internal void ReplaceNode(SyntaxNode node, Func<SyntaxNode, SyntaxGenerator, IEnumerable<SyntaxNode>> computeReplacement) { CheckNodeInOriginalTreeOrTracked(node); if (computeReplacement == null) { throw new ArgumentNullException(nameof(computeReplacement)); } _allowEditsOnLazilyCreatedTrackedNewNodes = true; _changes.Add(new ReplaceWithCollectionChange(node, computeReplacement, this)); } internal void ReplaceNode<TArgument>(SyntaxNode node, Func<SyntaxNode, SyntaxGenerator, TArgument, SyntaxNode> computeReplacement, TArgument argument) { CheckNodeInOriginalTreeOrTracked(node); if (computeReplacement == null) { throw new ArgumentNullException(nameof(computeReplacement)); } _allowEditsOnLazilyCreatedTrackedNewNodes = true; _changes.Add(new ReplaceChange<TArgument>(node, computeReplacement, argument, this)); } /// <summary> /// Replace the specified node with a different node. /// </summary> /// <param name="node">The node to replace that already exists in the tree.</param> /// <param name="newNode">The new node that will be placed into the tree in the existing node's location.</param> public void ReplaceNode(SyntaxNode node, SyntaxNode newNode) { CheckNodeInOriginalTreeOrTracked(node); if (node == newNode) { return; } newNode = ApplyTrackingToNewNode(newNode); _changes.Add(new ReplaceChange(node, (n, g) => newNode, this)); } /// <summary> /// Insert the new nodes before the specified node already existing in the tree. /// </summary> /// <param name="node">The node already existing in the tree that the new nodes will be placed before. This must be a node this is contained within a syntax list.</param> /// <param name="newNodes">The nodes to place before the existing node. These nodes must be of a compatible type to be placed in the same list containing the existing node.</param> public void InsertBefore(SyntaxNode node, IEnumerable<SyntaxNode> newNodes) { CheckNodeInOriginalTreeOrTracked(node); if (newNodes == null) { throw new ArgumentNullException(nameof(newNodes)); } newNodes = ApplyTrackingToNewNodes(newNodes); _changes.Add(new InsertChange(node, newNodes, isBefore: true)); } /// <summary> /// Insert the new node before the specified node already existing in the tree. /// </summary> /// <param name="node">The node already existing in the tree that the new nodes will be placed before. This must be a node this is contained within a syntax list.</param> /// <param name="newNode">The node to place before the existing node. This node must be of a compatible type to be placed in the same list containing the existing node.</param> public void InsertBefore(SyntaxNode node, SyntaxNode newNode) => InsertBefore(node, new[] { newNode }); /// <summary> /// Insert the new nodes after the specified node already existing in the tree. /// </summary> /// <param name="node">The node already existing in the tree that the new nodes will be placed after. This must be a node this is contained within a syntax list.</param> /// <param name="newNodes">The nodes to place after the existing node. These nodes must be of a compatible type to be placed in the same list containing the existing node.</param> public void InsertAfter(SyntaxNode node, IEnumerable<SyntaxNode> newNodes) { CheckNodeInOriginalTreeOrTracked(node); if (newNodes == null) { throw new ArgumentNullException(nameof(newNodes)); } newNodes = ApplyTrackingToNewNodes(newNodes); _changes.Add(new InsertChange(node, newNodes, isBefore: false)); } /// <summary> /// Insert the new node after the specified node already existing in the tree. /// </summary> /// <param name="node">The node already existing in the tree that the new nodes will be placed after. This must be a node this is contained within a syntax list.</param> /// <param name="newNode">The node to place after the existing node. This node must be of a compatible type to be placed in the same list containing the existing node.</param> public void InsertAfter(SyntaxNode node, SyntaxNode newNode) => this.InsertAfter(node, new[] { newNode }); private void CheckNodeInOriginalTreeOrTracked(SyntaxNode node) { if (node == null) { throw new ArgumentNullException(nameof(node)); } if (OriginalRoot.Contains(node)) { // Node is contained in the original tree. return; } if (_allowEditsOnLazilyCreatedTrackedNewNodes) { // This could be a node that is handed to us lazily from one of the prior edits // which support lazy replacement nodes, we conservatively avoid throwing here. // If this was indeed an unsupported node, syntax editor will throw an exception later // when attempting to compute changed root. return; } if (_lazyTrackedNewNodesOpt?.Contains(node) == true) { // Node is one of the new nodes, which is already tracked and supported. return; } throw new ArgumentException(WorkspacesResources.The_node_is_not_part_of_the_tree, nameof(node)); } private abstract class Change { internal readonly SyntaxNode Node; public Change(SyntaxNode node) => this.Node = node; public abstract SyntaxNode Apply(SyntaxNode root, SyntaxGenerator generator); } private class NoChange : Change { public NoChange(SyntaxNode node) : base(node) { } public override SyntaxNode Apply(SyntaxNode root, SyntaxGenerator generator) => root; } private class RemoveChange : Change { private readonly SyntaxRemoveOptions _options; public RemoveChange(SyntaxNode node, SyntaxRemoveOptions options) : base(node) { _options = options; } public override SyntaxNode Apply(SyntaxNode root, SyntaxGenerator generator) => generator.RemoveNode(root, root.GetCurrentNode(this.Node), _options); } private class ReplaceChange : Change { private readonly Func<SyntaxNode, SyntaxGenerator, SyntaxNode?> _modifier; private readonly SyntaxEditor _editor; public ReplaceChange( SyntaxNode node, Func<SyntaxNode, SyntaxGenerator, SyntaxNode?> modifier, SyntaxEditor editor) : base(node) { Contract.ThrowIfNull(node, "Passed in node is null."); _modifier = modifier; _editor = editor; } public override SyntaxNode Apply(SyntaxNode root, SyntaxGenerator generator) { var current = root.GetCurrentNode(this.Node); if (current is null) { Contract.Fail($"GetCurrentNode returned null with the following node: {this.Node}"); } var newNode = _modifier(current, generator); newNode = _editor.ApplyTrackingToNewNode(newNode); return generator.ReplaceNode(root, current, newNode); } } private class ReplaceWithCollectionChange : Change { private readonly Func<SyntaxNode, SyntaxGenerator, IEnumerable<SyntaxNode>> _modifier; private readonly SyntaxEditor _editor; public ReplaceWithCollectionChange( SyntaxNode node, Func<SyntaxNode, SyntaxGenerator, IEnumerable<SyntaxNode>> modifier, SyntaxEditor editor) : base(node) { _modifier = modifier; _editor = editor; } public override SyntaxNode Apply(SyntaxNode root, SyntaxGenerator generator) { var current = root.GetCurrentNode(this.Node); if (current is null) { Contract.Fail($"GetCurrentNode returned null with the following node: {this.Node}"); } var newNodes = _modifier(current, generator).ToList(); for (var i = 0; i < newNodes.Count; i++) { newNodes[i] = _editor.ApplyTrackingToNewNode(newNodes[i]); } return SyntaxGenerator.ReplaceNode(root, current, newNodes); } } private class ReplaceChange<TArgument> : Change { private readonly Func<SyntaxNode, SyntaxGenerator, TArgument, SyntaxNode> _modifier; private readonly TArgument _argument; private readonly SyntaxEditor _editor; public ReplaceChange( SyntaxNode node, Func<SyntaxNode, SyntaxGenerator, TArgument, SyntaxNode> modifier, TArgument argument, SyntaxEditor editor) : base(node) { _modifier = modifier; _argument = argument; _editor = editor; } public override SyntaxNode Apply(SyntaxNode root, SyntaxGenerator generator) { var current = root.GetCurrentNode(this.Node); if (current is null) { Contract.Fail($"GetCurrentNode returned null with the following node: {this.Node}"); } var newNode = _modifier(current, generator, _argument); newNode = _editor.ApplyTrackingToNewNode(newNode); return generator.ReplaceNode(root, current, newNode); } } private class InsertChange : Change { private readonly List<SyntaxNode> _newNodes; private readonly bool _isBefore; public InsertChange(SyntaxNode node, IEnumerable<SyntaxNode> newNodes, bool isBefore) : base(node) { _newNodes = newNodes.ToList(); _isBefore = isBefore; } public override SyntaxNode Apply(SyntaxNode root, SyntaxGenerator generator) { if (_isBefore) { return generator.InsertNodesBefore(root, root.GetCurrentNode(this.Node), _newNodes); } else { return generator.InsertNodesAfter(root, root.GetCurrentNode(this.Node), _newNodes); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editing { /// <summary> /// An editor for making changes to a syntax tree. /// </summary> public class SyntaxEditor { private readonly SyntaxGenerator _generator; private readonly List<Change> _changes; private bool _allowEditsOnLazilyCreatedTrackedNewNodes; private HashSet<SyntaxNode>? _lazyTrackedNewNodesOpt; /// <summary> /// Creates a new <see cref="SyntaxEditor"/> instance. /// </summary> public SyntaxEditor(SyntaxNode root, Workspace workspace) { if (workspace == null) { throw new ArgumentNullException(nameof(workspace)); } OriginalRoot = root ?? throw new ArgumentNullException(nameof(root)); _generator = SyntaxGenerator.GetGenerator(workspace, root.Language); _changes = new List<Change>(); } internal SyntaxEditor(SyntaxNode root, SyntaxGenerator generator) { OriginalRoot = root ?? throw new ArgumentNullException(nameof(root)); _generator = generator; _changes = new List<Change>(); } [return: NotNullIfNotNull("node")] private SyntaxNode? ApplyTrackingToNewNode(SyntaxNode? node) { if (node == null) { return null; } _lazyTrackedNewNodesOpt ??= new HashSet<SyntaxNode>(); foreach (var descendant in node.DescendantNodesAndSelf()) { _lazyTrackedNewNodesOpt.Add(descendant); } return node.TrackNodes(node.DescendantNodesAndSelf()); } private IEnumerable<SyntaxNode> ApplyTrackingToNewNodes(IEnumerable<SyntaxNode> nodes) { foreach (var node in nodes) { var result = ApplyTrackingToNewNode(node); yield return result; } } /// <summary> /// The <see cref="SyntaxNode"/> that was specified when the <see cref="SyntaxEditor"/> was constructed. /// </summary> public SyntaxNode OriginalRoot { get; } /// <summary> /// A <see cref="SyntaxGenerator"/> to use to create and change <see cref="SyntaxNode"/>'s. /// </summary> public SyntaxGenerator Generator => _generator; /// <summary> /// Returns the changed root node. /// </summary> public SyntaxNode GetChangedRoot() { var nodes = Enumerable.Distinct(_changes.Where(c => OriginalRoot.Contains(c.Node)) .Select(c => c.Node)); var newRoot = OriginalRoot.TrackNodes(nodes); foreach (var change in _changes) { newRoot = change.Apply(newRoot, _generator); } return newRoot; } /// <summary> /// Makes sure the node is tracked, even if it is not changed. /// </summary> public void TrackNode(SyntaxNode node) { CheckNodeInOriginalTreeOrTracked(node); _changes.Add(new NoChange(node)); } /// <summary> /// Remove the node from the tree. /// </summary> /// <param name="node">The node to remove that currently exists as part of the tree.</param> public void RemoveNode(SyntaxNode node) => RemoveNode(node, SyntaxGenerator.DefaultRemoveOptions); /// <summary> /// Remove the node from the tree. /// </summary> /// <param name="node">The node to remove that currently exists as part of the tree.</param> /// <param name="options">Options that affect how node removal works.</param> public void RemoveNode(SyntaxNode node, SyntaxRemoveOptions options) { CheckNodeInOriginalTreeOrTracked(node); _changes.Add(new RemoveChange(node, options)); } /// <summary> /// Replace the specified node with a node produced by the function. /// </summary> /// <param name="node">The node to replace that already exists in the tree.</param> /// <param name="computeReplacement">A function that computes a replacement node. /// The node passed into the compute function includes changes from prior edits. It will not appear as a descendant of the original root.</param> public void ReplaceNode(SyntaxNode node, Func<SyntaxNode, SyntaxGenerator, SyntaxNode> computeReplacement) { CheckNodeInOriginalTreeOrTracked(node); if (computeReplacement == null) { throw new ArgumentNullException(nameof(computeReplacement)); } _allowEditsOnLazilyCreatedTrackedNewNodes = true; _changes.Add(new ReplaceChange(node, computeReplacement, this)); } internal void ReplaceNode(SyntaxNode node, Func<SyntaxNode, SyntaxGenerator, IEnumerable<SyntaxNode>> computeReplacement) { CheckNodeInOriginalTreeOrTracked(node); if (computeReplacement == null) { throw new ArgumentNullException(nameof(computeReplacement)); } _allowEditsOnLazilyCreatedTrackedNewNodes = true; _changes.Add(new ReplaceWithCollectionChange(node, computeReplacement, this)); } internal void ReplaceNode<TArgument>(SyntaxNode node, Func<SyntaxNode, SyntaxGenerator, TArgument, SyntaxNode> computeReplacement, TArgument argument) { CheckNodeInOriginalTreeOrTracked(node); if (computeReplacement == null) { throw new ArgumentNullException(nameof(computeReplacement)); } _allowEditsOnLazilyCreatedTrackedNewNodes = true; _changes.Add(new ReplaceChange<TArgument>(node, computeReplacement, argument, this)); } /// <summary> /// Replace the specified node with a different node. /// </summary> /// <param name="node">The node to replace that already exists in the tree.</param> /// <param name="newNode">The new node that will be placed into the tree in the existing node's location.</param> public void ReplaceNode(SyntaxNode node, SyntaxNode newNode) { CheckNodeInOriginalTreeOrTracked(node); if (node == newNode) { return; } newNode = ApplyTrackingToNewNode(newNode); _changes.Add(new ReplaceChange(node, (n, g) => newNode, this)); } /// <summary> /// Insert the new nodes before the specified node already existing in the tree. /// </summary> /// <param name="node">The node already existing in the tree that the new nodes will be placed before. This must be a node this is contained within a syntax list.</param> /// <param name="newNodes">The nodes to place before the existing node. These nodes must be of a compatible type to be placed in the same list containing the existing node.</param> public void InsertBefore(SyntaxNode node, IEnumerable<SyntaxNode> newNodes) { CheckNodeInOriginalTreeOrTracked(node); if (newNodes == null) { throw new ArgumentNullException(nameof(newNodes)); } newNodes = ApplyTrackingToNewNodes(newNodes); _changes.Add(new InsertChange(node, newNodes, isBefore: true)); } /// <summary> /// Insert the new node before the specified node already existing in the tree. /// </summary> /// <param name="node">The node already existing in the tree that the new nodes will be placed before. This must be a node this is contained within a syntax list.</param> /// <param name="newNode">The node to place before the existing node. This node must be of a compatible type to be placed in the same list containing the existing node.</param> public void InsertBefore(SyntaxNode node, SyntaxNode newNode) => InsertBefore(node, new[] { newNode }); /// <summary> /// Insert the new nodes after the specified node already existing in the tree. /// </summary> /// <param name="node">The node already existing in the tree that the new nodes will be placed after. This must be a node this is contained within a syntax list.</param> /// <param name="newNodes">The nodes to place after the existing node. These nodes must be of a compatible type to be placed in the same list containing the existing node.</param> public void InsertAfter(SyntaxNode node, IEnumerable<SyntaxNode> newNodes) { CheckNodeInOriginalTreeOrTracked(node); if (newNodes == null) { throw new ArgumentNullException(nameof(newNodes)); } newNodes = ApplyTrackingToNewNodes(newNodes); _changes.Add(new InsertChange(node, newNodes, isBefore: false)); } /// <summary> /// Insert the new node after the specified node already existing in the tree. /// </summary> /// <param name="node">The node already existing in the tree that the new nodes will be placed after. This must be a node this is contained within a syntax list.</param> /// <param name="newNode">The node to place after the existing node. This node must be of a compatible type to be placed in the same list containing the existing node.</param> public void InsertAfter(SyntaxNode node, SyntaxNode newNode) => this.InsertAfter(node, new[] { newNode }); private void CheckNodeInOriginalTreeOrTracked(SyntaxNode node) { if (node == null) { throw new ArgumentNullException(nameof(node)); } if (OriginalRoot.Contains(node)) { // Node is contained in the original tree. return; } if (_allowEditsOnLazilyCreatedTrackedNewNodes) { // This could be a node that is handed to us lazily from one of the prior edits // which support lazy replacement nodes, we conservatively avoid throwing here. // If this was indeed an unsupported node, syntax editor will throw an exception later // when attempting to compute changed root. return; } if (_lazyTrackedNewNodesOpt?.Contains(node) == true) { // Node is one of the new nodes, which is already tracked and supported. return; } throw new ArgumentException(WorkspacesResources.The_node_is_not_part_of_the_tree, nameof(node)); } private abstract class Change { internal readonly SyntaxNode Node; public Change(SyntaxNode node) => this.Node = node; public abstract SyntaxNode Apply(SyntaxNode root, SyntaxGenerator generator); } private class NoChange : Change { public NoChange(SyntaxNode node) : base(node) { } public override SyntaxNode Apply(SyntaxNode root, SyntaxGenerator generator) => root; } private class RemoveChange : Change { private readonly SyntaxRemoveOptions _options; public RemoveChange(SyntaxNode node, SyntaxRemoveOptions options) : base(node) { _options = options; } public override SyntaxNode Apply(SyntaxNode root, SyntaxGenerator generator) => generator.RemoveNode(root, root.GetCurrentNode(this.Node), _options); } private class ReplaceChange : Change { private readonly Func<SyntaxNode, SyntaxGenerator, SyntaxNode?> _modifier; private readonly SyntaxEditor _editor; public ReplaceChange( SyntaxNode node, Func<SyntaxNode, SyntaxGenerator, SyntaxNode?> modifier, SyntaxEditor editor) : base(node) { Contract.ThrowIfNull(node, "Passed in node is null."); _modifier = modifier; _editor = editor; } public override SyntaxNode Apply(SyntaxNode root, SyntaxGenerator generator) { var current = root.GetCurrentNode(this.Node); if (current is null) { Contract.Fail($"GetCurrentNode returned null with the following node: {this.Node}"); } var newNode = _modifier(current, generator); newNode = _editor.ApplyTrackingToNewNode(newNode); return generator.ReplaceNode(root, current, newNode); } } private class ReplaceWithCollectionChange : Change { private readonly Func<SyntaxNode, SyntaxGenerator, IEnumerable<SyntaxNode>> _modifier; private readonly SyntaxEditor _editor; public ReplaceWithCollectionChange( SyntaxNode node, Func<SyntaxNode, SyntaxGenerator, IEnumerable<SyntaxNode>> modifier, SyntaxEditor editor) : base(node) { _modifier = modifier; _editor = editor; } public override SyntaxNode Apply(SyntaxNode root, SyntaxGenerator generator) { var current = root.GetCurrentNode(this.Node); if (current is null) { Contract.Fail($"GetCurrentNode returned null with the following node: {this.Node}"); } var newNodes = _modifier(current, generator).ToList(); for (var i = 0; i < newNodes.Count; i++) { newNodes[i] = _editor.ApplyTrackingToNewNode(newNodes[i]); } return SyntaxGenerator.ReplaceNode(root, current, newNodes); } } private class ReplaceChange<TArgument> : Change { private readonly Func<SyntaxNode, SyntaxGenerator, TArgument, SyntaxNode> _modifier; private readonly TArgument _argument; private readonly SyntaxEditor _editor; public ReplaceChange( SyntaxNode node, Func<SyntaxNode, SyntaxGenerator, TArgument, SyntaxNode> modifier, TArgument argument, SyntaxEditor editor) : base(node) { _modifier = modifier; _argument = argument; _editor = editor; } public override SyntaxNode Apply(SyntaxNode root, SyntaxGenerator generator) { var current = root.GetCurrentNode(this.Node); if (current is null) { Contract.Fail($"GetCurrentNode returned null with the following node: {this.Node}"); } var newNode = _modifier(current, generator, _argument); newNode = _editor.ApplyTrackingToNewNode(newNode); return generator.ReplaceNode(root, current, newNode); } } private class InsertChange : Change { private readonly List<SyntaxNode> _newNodes; private readonly bool _isBefore; public InsertChange(SyntaxNode node, IEnumerable<SyntaxNode> newNodes, bool isBefore) : base(node) { _newNodes = newNodes.ToList(); _isBefore = isBefore; } public override SyntaxNode Apply(SyntaxNode root, SyntaxGenerator generator) { if (_isBefore) { return generator.InsertNodesBefore(root, root.GetCurrentNode(this.Node), _newNodes); } else { return generator.InsertNodesAfter(root, root.GetCurrentNode(this.Node), _newNodes); } } } } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/EditorFeatures/CSharpTest2/Recommendations/BaseKeywordRecommenderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class BaseKeywordRecommenderTests : 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 TestNotInTopLevelMethod() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"void Goo() { $$ }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalStatement() { await VerifyAbsenceAsync( @"System.Console.WriteLine(); $$", options: CSharp9ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalVariableDeclaration() { await VerifyAbsenceAsync( @"int i = 0; $$", options: CSharp9ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInClassConstructorInitializer() { await VerifyKeywordAsync( @"class C { public C() : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInRecordConstructorInitializer() { // The recommender doesn't work in record in script // Tracked by https://github.com/dotnet/roslyn/issues/44865 await VerifyWorkerAsync(@" record C { public C() : $$", absent: false, options: TestOptions.RegularPreview); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInStaticClassConstructorInitializer() { await VerifyAbsenceAsync( @"class C { static C() : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInStructConstructorInitializer() { await VerifyAbsenceAsync( @"struct C { public C() : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterCast() { await VerifyKeywordAsync( @"struct C { new internal ErrorCode Code { get { return (ErrorCode)$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInEmptyMethod() { await VerifyKeywordAsync( SourceCodeKind.Regular, AddInsideMethod( @"$$")); } [WorkItem(538264, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538264")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEnumMemberInitializer1() { await VerifyAbsenceAsync( @"enum E { a = $$ }"); } [WorkItem(544219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInObjectInitializerMemberContext() { await VerifyAbsenceAsync(@" class C { public int x, y; void M() { var c = new C { x = 2, y = 3, $$"); } [WorkItem(16335, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/16335")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task InExpressionBodyAccessor() { await VerifyKeywordAsync(@" class B { public virtual int T { get => bas$$ } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefExpression() { await VerifyKeywordAsync(AddInsideMethod( @"ref int x = ref $$")); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class BaseKeywordRecommenderTests : 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 TestNotInTopLevelMethod() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"void Goo() { $$ }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalStatement() { await VerifyAbsenceAsync( @"System.Console.WriteLine(); $$", options: CSharp9ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalVariableDeclaration() { await VerifyAbsenceAsync( @"int i = 0; $$", options: CSharp9ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInClassConstructorInitializer() { await VerifyKeywordAsync( @"class C { public C() : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInRecordConstructorInitializer() { // The recommender doesn't work in record in script // Tracked by https://github.com/dotnet/roslyn/issues/44865 await VerifyWorkerAsync(@" record C { public C() : $$", absent: false, options: TestOptions.RegularPreview); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInStaticClassConstructorInitializer() { await VerifyAbsenceAsync( @"class C { static C() : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInStructConstructorInitializer() { await VerifyAbsenceAsync( @"struct C { public C() : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterCast() { await VerifyKeywordAsync( @"struct C { new internal ErrorCode Code { get { return (ErrorCode)$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInEmptyMethod() { await VerifyKeywordAsync( SourceCodeKind.Regular, AddInsideMethod( @"$$")); } [WorkItem(538264, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538264")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEnumMemberInitializer1() { await VerifyAbsenceAsync( @"enum E { a = $$ }"); } [WorkItem(544219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInObjectInitializerMemberContext() { await VerifyAbsenceAsync(@" class C { public int x, y; void M() { var c = new C { x = 2, y = 3, $$"); } [WorkItem(16335, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/16335")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task InExpressionBodyAccessor() { await VerifyKeywordAsync(@" class B { public virtual int T { get => bas$$ } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefExpression() { await VerifyKeywordAsync(AddInsideMethod( @"ref int x = ref $$")); } } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/Analyzers/Core/Analyzers/PopulateSwitch/AbstractPopulateSwitchExpressionDiagnosticAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; namespace Microsoft.CodeAnalysis.PopulateSwitch { internal abstract class AbstractPopulateSwitchExpressionDiagnosticAnalyzer<TSwitchSyntax> : AbstractPopulateSwitchDiagnosticAnalyzer<ISwitchExpressionOperation, TSwitchSyntax> where TSwitchSyntax : SyntaxNode { protected AbstractPopulateSwitchExpressionDiagnosticAnalyzer() : base(IDEDiagnosticIds.PopulateSwitchExpressionDiagnosticId, EnforceOnBuildValues.PopulateSwitchExpression) { } protected sealed override OperationKind OperationKind => OperationKind.SwitchExpression; protected sealed override ICollection<ISymbol> GetMissingEnumMembers(ISwitchExpressionOperation operation) => PopulateSwitchExpressionHelpers.GetMissingEnumMembers(operation); protected sealed override bool HasDefaultCase(ISwitchExpressionOperation operation) => PopulateSwitchExpressionHelpers.HasDefaultCase(operation); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; namespace Microsoft.CodeAnalysis.PopulateSwitch { internal abstract class AbstractPopulateSwitchExpressionDiagnosticAnalyzer<TSwitchSyntax> : AbstractPopulateSwitchDiagnosticAnalyzer<ISwitchExpressionOperation, TSwitchSyntax> where TSwitchSyntax : SyntaxNode { protected AbstractPopulateSwitchExpressionDiagnosticAnalyzer() : base(IDEDiagnosticIds.PopulateSwitchExpressionDiagnosticId, EnforceOnBuildValues.PopulateSwitchExpression) { } protected sealed override OperationKind OperationKind => OperationKind.SwitchExpression; protected sealed override ICollection<ISymbol> GetMissingEnumMembers(ISwitchExpressionOperation operation) => PopulateSwitchExpressionHelpers.GetMissingEnumMembers(operation); protected sealed override bool HasDefaultCase(ISwitchExpressionOperation operation) => PopulateSwitchExpressionHelpers.HasDefaultCase(operation); } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/Compilers/Core/Portable/CodeAnalysisResourcesLocalizableErrorArgument.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Globalization; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal struct CodeAnalysisResourcesLocalizableErrorArgument : IFormattable { private readonly string _targetResourceId; internal CodeAnalysisResourcesLocalizableErrorArgument(string targetResourceId) { RoslynDebug.Assert(targetResourceId != null); _targetResourceId = targetResourceId; } public override string ToString() { return ToString(null, null); } public string ToString(string? format, IFormatProvider? formatProvider) { if (_targetResourceId != null) { return CodeAnalysisResources.ResourceManager.GetString(_targetResourceId, formatProvider as System.Globalization.CultureInfo) ?? string.Empty; } return string.Empty; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Globalization; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal struct CodeAnalysisResourcesLocalizableErrorArgument : IFormattable { private readonly string _targetResourceId; internal CodeAnalysisResourcesLocalizableErrorArgument(string targetResourceId) { RoslynDebug.Assert(targetResourceId != null); _targetResourceId = targetResourceId; } public override string ToString() { return ToString(null, null); } public string ToString(string? format, IFormatProvider? formatProvider) { if (_targetResourceId != null) { return CodeAnalysisResources.ResourceManager.GetString(_targetResourceId, formatProvider as System.Globalization.CultureInfo) ?? string.Empty; } return string.Empty; } } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/Compilers/CSharp/Portable/Syntax/SyntaxFacts.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.CSharp.SyntaxKind; namespace Microsoft.CodeAnalysis.CSharp { public static partial class SyntaxFacts { /// <summary> /// Returns true if the node is the alias of an AliasQualifiedNameSyntax /// </summary> public static bool IsAliasQualifier(SyntaxNode node) { var p = node.Parent as AliasQualifiedNameSyntax; return p != null && p.Alias == node; } public static bool IsAttributeName(SyntaxNode node) { var parent = node.Parent; if (parent == null || !IsName(node.Kind())) { return false; } switch (parent.Kind()) { case QualifiedName: var qn = (QualifiedNameSyntax)parent; return qn.Right == node ? IsAttributeName(parent) : false; case AliasQualifiedName: var an = (AliasQualifiedNameSyntax)parent; return an.Name == node ? IsAttributeName(parent) : false; } var p = node.Parent as AttributeSyntax; return p != null && p.Name == node; } /// <summary> /// Returns true if the node is the object of an invocation expression. /// </summary> public static bool IsInvoked(ExpressionSyntax node) { node = (ExpressionSyntax)SyntaxFactory.GetStandaloneExpression(node); var inv = node.Parent as InvocationExpressionSyntax; return inv != null && inv.Expression == node; } /// <summary> /// Returns true if the node is the object of an element access expression. /// </summary> public static bool IsIndexed(ExpressionSyntax node) { node = (ExpressionSyntax)SyntaxFactory.GetStandaloneExpression(node); var indexer = node.Parent as ElementAccessExpressionSyntax; return indexer != null && indexer.Expression == node; } public static bool IsNamespaceAliasQualifier(ExpressionSyntax node) { var parent = node.Parent as AliasQualifiedNameSyntax; return parent != null && parent.Alias == node; } /// <summary> /// Returns true if the node is in a tree location that is expected to be a type /// </summary> /// <param name="node"></param> /// <returns></returns> public static bool IsInTypeOnlyContext(ExpressionSyntax node) { node = SyntaxFactory.GetStandaloneExpression(node); var parent = node.Parent; if (parent != null) { switch (parent.Kind()) { case Attribute: return ((AttributeSyntax)parent).Name == node; case ArrayType: return ((ArrayTypeSyntax)parent).ElementType == node; case PointerType: return ((PointerTypeSyntax)parent).ElementType == node; case FunctionPointerType: // FunctionPointerTypeSyntax has no direct children that are ExpressionSyntaxes throw ExceptionUtilities.Unreachable; case PredefinedType: return true; case NullableType: return ((NullableTypeSyntax)parent).ElementType == node; case TypeArgumentList: // all children of GenericNames are type arguments return true; case CastExpression: return ((CastExpressionSyntax)parent).Type == node; case ObjectCreationExpression: return ((ObjectCreationExpressionSyntax)parent).Type == node; case StackAllocArrayCreationExpression: return ((StackAllocArrayCreationExpressionSyntax)parent).Type == node; case FromClause: return ((FromClauseSyntax)parent).Type == node; case JoinClause: return ((JoinClauseSyntax)parent).Type == node; case VariableDeclaration: return ((VariableDeclarationSyntax)parent).Type == node; case ForEachStatement: return ((ForEachStatementSyntax)parent).Type == node; case CatchDeclaration: return ((CatchDeclarationSyntax)parent).Type == node; case AsExpression: case IsExpression: return ((BinaryExpressionSyntax)parent).Right == node; case TypeOfExpression: return ((TypeOfExpressionSyntax)parent).Type == node; case SizeOfExpression: return ((SizeOfExpressionSyntax)parent).Type == node; case DefaultExpression: return ((DefaultExpressionSyntax)parent).Type == node; case RefValueExpression: return ((RefValueExpressionSyntax)parent).Type == node; case RefType: return ((RefTypeSyntax)parent).Type == node; case Parameter: case FunctionPointerParameter: return ((BaseParameterSyntax)parent).Type == node; case TypeConstraint: return ((TypeConstraintSyntax)parent).Type == node; case MethodDeclaration: return ((MethodDeclarationSyntax)parent).ReturnType == node; case IndexerDeclaration: return ((IndexerDeclarationSyntax)parent).Type == node; case OperatorDeclaration: return ((OperatorDeclarationSyntax)parent).ReturnType == node; case ConversionOperatorDeclaration: return ((ConversionOperatorDeclarationSyntax)parent).Type == node; case PropertyDeclaration: return ((PropertyDeclarationSyntax)parent).Type == node; case DelegateDeclaration: return ((DelegateDeclarationSyntax)parent).ReturnType == node; case EventDeclaration: return ((EventDeclarationSyntax)parent).Type == node; case LocalFunctionStatement: return ((LocalFunctionStatementSyntax)parent).ReturnType == node; case ParenthesizedLambdaExpression: return ((ParenthesizedLambdaExpressionSyntax)parent).ReturnType == node; case SimpleBaseType: return true; case PrimaryConstructorBaseType: return ((PrimaryConstructorBaseTypeSyntax)parent).Type == node; case CrefParameter: return true; case ConversionOperatorMemberCref: return ((ConversionOperatorMemberCrefSyntax)parent).Type == node; case ExplicitInterfaceSpecifier: // #13.4.1 An explicit member implementation is a method, property, event or indexer // declaration that references a fully qualified interface member name. // A ExplicitInterfaceSpecifier represents the left part (QN) of the member name, so it // should be treated like a QualifiedName. return ((ExplicitInterfaceSpecifierSyntax)parent).Name == node; case DeclarationPattern: return ((DeclarationPatternSyntax)parent).Type == node; case RecursivePattern: return ((RecursivePatternSyntax)parent).Type == node; case TupleElement: return ((TupleElementSyntax)parent).Type == node; case DeclarationExpression: return ((DeclarationExpressionSyntax)parent).Type == node; case IncompleteMember: return ((IncompleteMemberSyntax)parent).Type == node; } } return false; } /// <summary> /// Returns true if a node is in a tree location that is expected to be either a namespace or type /// </summary> /// <param name="node"></param> /// <returns></returns> public static bool IsInNamespaceOrTypeContext(ExpressionSyntax? node) { if (node != null) { node = (ExpressionSyntax)SyntaxFactory.GetStandaloneExpression(node); var parent = node.Parent; if (parent != null) { switch (parent.Kind()) { case UsingDirective: return ((UsingDirectiveSyntax)parent).Name == node; case QualifiedName: // left of QN is namespace or type. Note: when you have "a.b.c()", then // "a.b" is not a qualified name, it is a member access expression. // Qualified names are only parsed when the parser knows it's a type only // context. return ((QualifiedNameSyntax)parent).Left == node; default: return IsInTypeOnlyContext(node); } } } return false; } /// <summary> /// Is the node the name of a named argument of an invocation, object creation expression, /// constructor initializer, or element access, but not an attribute. /// </summary> public static bool IsNamedArgumentName(SyntaxNode node) { // An argument name is an IdentifierName inside a NameColon, inside an Argument, inside an ArgumentList, inside an // Invocation, ObjectCreation, ObjectInitializer, ElementAccess or Subpattern. if (!node.IsKind(IdentifierName)) { return false; } var parent1 = node.Parent; if (parent1 == null || !parent1.IsKind(NameColon)) { return false; } var parent2 = parent1.Parent; if (parent2.IsKind(SyntaxKind.Subpattern)) { return true; } if (parent2 == null || !(parent2.IsKind(Argument) || parent2.IsKind(AttributeArgument))) { return false; } var parent3 = parent2.Parent; if (parent3 == null) { return false; } if (parent3.IsKind(SyntaxKind.TupleExpression)) { return true; } if (!(parent3 is BaseArgumentListSyntax || parent3.IsKind(AttributeArgumentList))) { return false; } var parent4 = parent3.Parent; if (parent4 == null) { return false; } switch (parent4.Kind()) { case InvocationExpression: case TupleExpression: case ObjectCreationExpression: case ImplicitObjectCreationExpression: case ObjectInitializerExpression: case ElementAccessExpression: case Attribute: case BaseConstructorInitializer: case ThisConstructorInitializer: case PrimaryConstructorBaseType: return true; default: return false; } } /// <summary> /// Is the expression the initializer in a fixed statement? /// </summary> public static bool IsFixedStatementExpression(SyntaxNode node) { var current = node.Parent; // Dig through parens because dev10 does (even though the spec doesn't say so) // Dig through casts because there's a special error code (CS0254) for such casts. while (current != null && (current.IsKind(ParenthesizedExpression) || current.IsKind(CastExpression))) current = current.Parent; if (current == null || !current.IsKind(EqualsValueClause)) return false; current = current.Parent; if (current == null || !current.IsKind(VariableDeclarator)) return false; current = current.Parent; if (current == null || !current.IsKind(VariableDeclaration)) return false; current = current.Parent; return current != null && current.IsKind(FixedStatement); } public static string GetText(Accessibility accessibility) { switch (accessibility) { case Accessibility.NotApplicable: return string.Empty; case Accessibility.Private: return SyntaxFacts.GetText(PrivateKeyword); case Accessibility.ProtectedAndInternal: return SyntaxFacts.GetText(PrivateKeyword) + " " + SyntaxFacts.GetText(ProtectedKeyword); case Accessibility.Internal: return SyntaxFacts.GetText(InternalKeyword); case Accessibility.Protected: return SyntaxFacts.GetText(ProtectedKeyword); case Accessibility.ProtectedOrInternal: return SyntaxFacts.GetText(ProtectedKeyword) + " " + SyntaxFacts.GetText(InternalKeyword); case Accessibility.Public: return SyntaxFacts.GetText(PublicKeyword); default: throw ExceptionUtilities.UnexpectedValue(accessibility); } } internal static bool IsStatementExpression(SyntaxNode syntax) { // The grammar gives: // // expression-statement: // statement-expression ; // // statement-expression: // invocation-expression // object-creation-expression // assignment // post-increment-expression // post-decrement-expression // pre-increment-expression // pre-decrement-expression // await-expression switch (syntax.Kind()) { case InvocationExpression: case ObjectCreationExpression: case SimpleAssignmentExpression: case AddAssignmentExpression: case SubtractAssignmentExpression: case MultiplyAssignmentExpression: case DivideAssignmentExpression: case ModuloAssignmentExpression: case AndAssignmentExpression: case OrAssignmentExpression: case ExclusiveOrAssignmentExpression: case LeftShiftAssignmentExpression: case RightShiftAssignmentExpression: case CoalesceAssignmentExpression: case PostIncrementExpression: case PostDecrementExpression: case PreIncrementExpression: case PreDecrementExpression: case AwaitExpression: return true; case ConditionalAccessExpression: var access = (ConditionalAccessExpressionSyntax)syntax; return IsStatementExpression(access.WhenNotNull); // Allow missing IdentifierNames; they will show up in error cases // where there is no statement whatsoever. case IdentifierName: return syntax.IsMissing; default: return false; } } [System.Obsolete("IsLambdaBody API is obsolete", true)] public static bool IsLambdaBody(SyntaxNode node) { return LambdaUtilities.IsLambdaBody(node); } internal static bool IsIdentifierVar(this Syntax.InternalSyntax.SyntaxToken node) { return node.ContextualKind == SyntaxKind.VarKeyword; } internal static bool IsIdentifierVarOrPredefinedType(this Syntax.InternalSyntax.SyntaxToken node) { return node.IsIdentifierVar() || IsPredefinedType(node.Kind); } internal static bool IsDeclarationExpressionType(SyntaxNode node, [NotNullWhen(true)] out DeclarationExpressionSyntax? parent) { parent = node.Parent as DeclarationExpressionSyntax; return node == parent?.Type; } /// <summary> /// Given an initializer expression infer the name of anonymous property or tuple element. /// Returns null if unsuccessful /// </summary> public static string? TryGetInferredMemberName(this SyntaxNode syntax) { SyntaxToken nameToken; switch (syntax.Kind()) { case SyntaxKind.SingleVariableDesignation: nameToken = ((SingleVariableDesignationSyntax)syntax).Identifier; break; case SyntaxKind.DeclarationExpression: var declaration = (DeclarationExpressionSyntax)syntax; var designationKind = declaration.Designation.Kind(); if (designationKind == SyntaxKind.ParenthesizedVariableDesignation || designationKind == SyntaxKind.DiscardDesignation) { return null; } nameToken = ((SingleVariableDesignationSyntax)declaration.Designation).Identifier; break; case SyntaxKind.ParenthesizedVariableDesignation: case SyntaxKind.DiscardDesignation: return null; default: if (syntax is ExpressionSyntax expr) { nameToken = expr.ExtractAnonymousTypeMemberName(); break; } return null; } return nameToken.RawKind != 0 ? nameToken.ValueText : null; } /// <summary> /// Checks whether the element name is reserved. /// /// For example: /// "Item3" is reserved (at certain positions). /// "Rest", "ToString" and other members of System.ValueTuple are reserved (in any position). /// Names that are not reserved return false. /// </summary> public static bool IsReservedTupleElementName(string elementName) { return NamedTypeSymbol.IsTupleElementNameReserved(elementName) != -1; } internal static bool HasAnyBody(this BaseMethodDeclarationSyntax declaration) { return (declaration.Body ?? (SyntaxNode?)declaration.ExpressionBody) != null; } internal static bool IsTopLevelStatement([NotNullWhen(true)] GlobalStatementSyntax? syntax) { return syntax?.Parent?.IsKind(SyntaxKind.CompilationUnit) == true; } internal static bool IsSimpleProgramTopLevelStatement(GlobalStatementSyntax? syntax) { return IsTopLevelStatement(syntax) && syntax.SyntaxTree.Options.Kind == SourceCodeKind.Regular; } internal static bool HasAwaitOperations(SyntaxNode node) { // Do not descend into functions return node.DescendantNodesAndSelf(child => !IsNestedFunction(child)).Any( node => { switch (node) { case AwaitExpressionSyntax _: case LocalDeclarationStatementSyntax local when local.AwaitKeyword.IsKind(SyntaxKind.AwaitKeyword): case CommonForEachStatementSyntax @foreach when @foreach.AwaitKeyword.IsKind(SyntaxKind.AwaitKeyword): case UsingStatementSyntax @using when @using.AwaitKeyword.IsKind(SyntaxKind.AwaitKeyword): return true; default: return false; } }); } internal static bool IsNestedFunction(SyntaxNode child) { switch (child.Kind()) { case SyntaxKind.LocalFunctionStatement: case SyntaxKind.AnonymousMethodExpression: case SyntaxKind.SimpleLambdaExpression: case SyntaxKind.ParenthesizedLambdaExpression: return true; default: return false; } } internal static bool HasYieldOperations(SyntaxNode? node) { // Do not descend into functions and expressions return node is object && node.DescendantNodesAndSelf(child => { Debug.Assert(ReferenceEquals(node, child) || child is not (MemberDeclarationSyntax or TypeDeclarationSyntax)); return !IsNestedFunction(child) && !(node is ExpressionSyntax); }).Any(n => n is YieldStatementSyntax); } internal static bool HasReturnWithExpression(SyntaxNode? node) { // Do not descend into functions and expressions return node is object && node.DescendantNodesAndSelf(child => !IsNestedFunction(child) && !(node is ExpressionSyntax)).Any(n => n is ReturnStatementSyntax { Expression: { } }); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.CSharp.SyntaxKind; namespace Microsoft.CodeAnalysis.CSharp { public static partial class SyntaxFacts { /// <summary> /// Returns true if the node is the alias of an AliasQualifiedNameSyntax /// </summary> public static bool IsAliasQualifier(SyntaxNode node) { var p = node.Parent as AliasQualifiedNameSyntax; return p != null && p.Alias == node; } public static bool IsAttributeName(SyntaxNode node) { var parent = node.Parent; if (parent == null || !IsName(node.Kind())) { return false; } switch (parent.Kind()) { case QualifiedName: var qn = (QualifiedNameSyntax)parent; return qn.Right == node ? IsAttributeName(parent) : false; case AliasQualifiedName: var an = (AliasQualifiedNameSyntax)parent; return an.Name == node ? IsAttributeName(parent) : false; } var p = node.Parent as AttributeSyntax; return p != null && p.Name == node; } /// <summary> /// Returns true if the node is the object of an invocation expression. /// </summary> public static bool IsInvoked(ExpressionSyntax node) { node = (ExpressionSyntax)SyntaxFactory.GetStandaloneExpression(node); var inv = node.Parent as InvocationExpressionSyntax; return inv != null && inv.Expression == node; } /// <summary> /// Returns true if the node is the object of an element access expression. /// </summary> public static bool IsIndexed(ExpressionSyntax node) { node = (ExpressionSyntax)SyntaxFactory.GetStandaloneExpression(node); var indexer = node.Parent as ElementAccessExpressionSyntax; return indexer != null && indexer.Expression == node; } public static bool IsNamespaceAliasQualifier(ExpressionSyntax node) { var parent = node.Parent as AliasQualifiedNameSyntax; return parent != null && parent.Alias == node; } /// <summary> /// Returns true if the node is in a tree location that is expected to be a type /// </summary> /// <param name="node"></param> /// <returns></returns> public static bool IsInTypeOnlyContext(ExpressionSyntax node) { node = SyntaxFactory.GetStandaloneExpression(node); var parent = node.Parent; if (parent != null) { switch (parent.Kind()) { case Attribute: return ((AttributeSyntax)parent).Name == node; case ArrayType: return ((ArrayTypeSyntax)parent).ElementType == node; case PointerType: return ((PointerTypeSyntax)parent).ElementType == node; case FunctionPointerType: // FunctionPointerTypeSyntax has no direct children that are ExpressionSyntaxes throw ExceptionUtilities.Unreachable; case PredefinedType: return true; case NullableType: return ((NullableTypeSyntax)parent).ElementType == node; case TypeArgumentList: // all children of GenericNames are type arguments return true; case CastExpression: return ((CastExpressionSyntax)parent).Type == node; case ObjectCreationExpression: return ((ObjectCreationExpressionSyntax)parent).Type == node; case StackAllocArrayCreationExpression: return ((StackAllocArrayCreationExpressionSyntax)parent).Type == node; case FromClause: return ((FromClauseSyntax)parent).Type == node; case JoinClause: return ((JoinClauseSyntax)parent).Type == node; case VariableDeclaration: return ((VariableDeclarationSyntax)parent).Type == node; case ForEachStatement: return ((ForEachStatementSyntax)parent).Type == node; case CatchDeclaration: return ((CatchDeclarationSyntax)parent).Type == node; case AsExpression: case IsExpression: return ((BinaryExpressionSyntax)parent).Right == node; case TypeOfExpression: return ((TypeOfExpressionSyntax)parent).Type == node; case SizeOfExpression: return ((SizeOfExpressionSyntax)parent).Type == node; case DefaultExpression: return ((DefaultExpressionSyntax)parent).Type == node; case RefValueExpression: return ((RefValueExpressionSyntax)parent).Type == node; case RefType: return ((RefTypeSyntax)parent).Type == node; case Parameter: case FunctionPointerParameter: return ((BaseParameterSyntax)parent).Type == node; case TypeConstraint: return ((TypeConstraintSyntax)parent).Type == node; case MethodDeclaration: return ((MethodDeclarationSyntax)parent).ReturnType == node; case IndexerDeclaration: return ((IndexerDeclarationSyntax)parent).Type == node; case OperatorDeclaration: return ((OperatorDeclarationSyntax)parent).ReturnType == node; case ConversionOperatorDeclaration: return ((ConversionOperatorDeclarationSyntax)parent).Type == node; case PropertyDeclaration: return ((PropertyDeclarationSyntax)parent).Type == node; case DelegateDeclaration: return ((DelegateDeclarationSyntax)parent).ReturnType == node; case EventDeclaration: return ((EventDeclarationSyntax)parent).Type == node; case LocalFunctionStatement: return ((LocalFunctionStatementSyntax)parent).ReturnType == node; case ParenthesizedLambdaExpression: return ((ParenthesizedLambdaExpressionSyntax)parent).ReturnType == node; case SimpleBaseType: return true; case PrimaryConstructorBaseType: return ((PrimaryConstructorBaseTypeSyntax)parent).Type == node; case CrefParameter: return true; case ConversionOperatorMemberCref: return ((ConversionOperatorMemberCrefSyntax)parent).Type == node; case ExplicitInterfaceSpecifier: // #13.4.1 An explicit member implementation is a method, property, event or indexer // declaration that references a fully qualified interface member name. // A ExplicitInterfaceSpecifier represents the left part (QN) of the member name, so it // should be treated like a QualifiedName. return ((ExplicitInterfaceSpecifierSyntax)parent).Name == node; case DeclarationPattern: return ((DeclarationPatternSyntax)parent).Type == node; case RecursivePattern: return ((RecursivePatternSyntax)parent).Type == node; case TupleElement: return ((TupleElementSyntax)parent).Type == node; case DeclarationExpression: return ((DeclarationExpressionSyntax)parent).Type == node; case IncompleteMember: return ((IncompleteMemberSyntax)parent).Type == node; } } return false; } /// <summary> /// Returns true if a node is in a tree location that is expected to be either a namespace or type /// </summary> /// <param name="node"></param> /// <returns></returns> public static bool IsInNamespaceOrTypeContext(ExpressionSyntax? node) { if (node != null) { node = (ExpressionSyntax)SyntaxFactory.GetStandaloneExpression(node); var parent = node.Parent; if (parent != null) { switch (parent.Kind()) { case UsingDirective: return ((UsingDirectiveSyntax)parent).Name == node; case QualifiedName: // left of QN is namespace or type. Note: when you have "a.b.c()", then // "a.b" is not a qualified name, it is a member access expression. // Qualified names are only parsed when the parser knows it's a type only // context. return ((QualifiedNameSyntax)parent).Left == node; default: return IsInTypeOnlyContext(node); } } } return false; } /// <summary> /// Is the node the name of a named argument of an invocation, object creation expression, /// constructor initializer, or element access, but not an attribute. /// </summary> public static bool IsNamedArgumentName(SyntaxNode node) { // An argument name is an IdentifierName inside a NameColon, inside an Argument, inside an ArgumentList, inside an // Invocation, ObjectCreation, ObjectInitializer, ElementAccess or Subpattern. if (!node.IsKind(IdentifierName)) { return false; } var parent1 = node.Parent; if (parent1 == null || !parent1.IsKind(NameColon)) { return false; } var parent2 = parent1.Parent; if (parent2.IsKind(SyntaxKind.Subpattern)) { return true; } if (parent2 == null || !(parent2.IsKind(Argument) || parent2.IsKind(AttributeArgument))) { return false; } var parent3 = parent2.Parent; if (parent3 == null) { return false; } if (parent3.IsKind(SyntaxKind.TupleExpression)) { return true; } if (!(parent3 is BaseArgumentListSyntax || parent3.IsKind(AttributeArgumentList))) { return false; } var parent4 = parent3.Parent; if (parent4 == null) { return false; } switch (parent4.Kind()) { case InvocationExpression: case TupleExpression: case ObjectCreationExpression: case ImplicitObjectCreationExpression: case ObjectInitializerExpression: case ElementAccessExpression: case Attribute: case BaseConstructorInitializer: case ThisConstructorInitializer: case PrimaryConstructorBaseType: return true; default: return false; } } /// <summary> /// Is the expression the initializer in a fixed statement? /// </summary> public static bool IsFixedStatementExpression(SyntaxNode node) { var current = node.Parent; // Dig through parens because dev10 does (even though the spec doesn't say so) // Dig through casts because there's a special error code (CS0254) for such casts. while (current != null && (current.IsKind(ParenthesizedExpression) || current.IsKind(CastExpression))) current = current.Parent; if (current == null || !current.IsKind(EqualsValueClause)) return false; current = current.Parent; if (current == null || !current.IsKind(VariableDeclarator)) return false; current = current.Parent; if (current == null || !current.IsKind(VariableDeclaration)) return false; current = current.Parent; return current != null && current.IsKind(FixedStatement); } public static string GetText(Accessibility accessibility) { switch (accessibility) { case Accessibility.NotApplicable: return string.Empty; case Accessibility.Private: return SyntaxFacts.GetText(PrivateKeyword); case Accessibility.ProtectedAndInternal: return SyntaxFacts.GetText(PrivateKeyword) + " " + SyntaxFacts.GetText(ProtectedKeyword); case Accessibility.Internal: return SyntaxFacts.GetText(InternalKeyword); case Accessibility.Protected: return SyntaxFacts.GetText(ProtectedKeyword); case Accessibility.ProtectedOrInternal: return SyntaxFacts.GetText(ProtectedKeyword) + " " + SyntaxFacts.GetText(InternalKeyword); case Accessibility.Public: return SyntaxFacts.GetText(PublicKeyword); default: throw ExceptionUtilities.UnexpectedValue(accessibility); } } internal static bool IsStatementExpression(SyntaxNode syntax) { // The grammar gives: // // expression-statement: // statement-expression ; // // statement-expression: // invocation-expression // object-creation-expression // assignment // post-increment-expression // post-decrement-expression // pre-increment-expression // pre-decrement-expression // await-expression switch (syntax.Kind()) { case InvocationExpression: case ObjectCreationExpression: case SimpleAssignmentExpression: case AddAssignmentExpression: case SubtractAssignmentExpression: case MultiplyAssignmentExpression: case DivideAssignmentExpression: case ModuloAssignmentExpression: case AndAssignmentExpression: case OrAssignmentExpression: case ExclusiveOrAssignmentExpression: case LeftShiftAssignmentExpression: case RightShiftAssignmentExpression: case CoalesceAssignmentExpression: case PostIncrementExpression: case PostDecrementExpression: case PreIncrementExpression: case PreDecrementExpression: case AwaitExpression: return true; case ConditionalAccessExpression: var access = (ConditionalAccessExpressionSyntax)syntax; return IsStatementExpression(access.WhenNotNull); // Allow missing IdentifierNames; they will show up in error cases // where there is no statement whatsoever. case IdentifierName: return syntax.IsMissing; default: return false; } } [System.Obsolete("IsLambdaBody API is obsolete", true)] public static bool IsLambdaBody(SyntaxNode node) { return LambdaUtilities.IsLambdaBody(node); } internal static bool IsIdentifierVar(this Syntax.InternalSyntax.SyntaxToken node) { return node.ContextualKind == SyntaxKind.VarKeyword; } internal static bool IsIdentifierVarOrPredefinedType(this Syntax.InternalSyntax.SyntaxToken node) { return node.IsIdentifierVar() || IsPredefinedType(node.Kind); } internal static bool IsDeclarationExpressionType(SyntaxNode node, [NotNullWhen(true)] out DeclarationExpressionSyntax? parent) { parent = node.Parent as DeclarationExpressionSyntax; return node == parent?.Type; } /// <summary> /// Given an initializer expression infer the name of anonymous property or tuple element. /// Returns null if unsuccessful /// </summary> public static string? TryGetInferredMemberName(this SyntaxNode syntax) { SyntaxToken nameToken; switch (syntax.Kind()) { case SyntaxKind.SingleVariableDesignation: nameToken = ((SingleVariableDesignationSyntax)syntax).Identifier; break; case SyntaxKind.DeclarationExpression: var declaration = (DeclarationExpressionSyntax)syntax; var designationKind = declaration.Designation.Kind(); if (designationKind == SyntaxKind.ParenthesizedVariableDesignation || designationKind == SyntaxKind.DiscardDesignation) { return null; } nameToken = ((SingleVariableDesignationSyntax)declaration.Designation).Identifier; break; case SyntaxKind.ParenthesizedVariableDesignation: case SyntaxKind.DiscardDesignation: return null; default: if (syntax is ExpressionSyntax expr) { nameToken = expr.ExtractAnonymousTypeMemberName(); break; } return null; } return nameToken.RawKind != 0 ? nameToken.ValueText : null; } /// <summary> /// Checks whether the element name is reserved. /// /// For example: /// "Item3" is reserved (at certain positions). /// "Rest", "ToString" and other members of System.ValueTuple are reserved (in any position). /// Names that are not reserved return false. /// </summary> public static bool IsReservedTupleElementName(string elementName) { return NamedTypeSymbol.IsTupleElementNameReserved(elementName) != -1; } internal static bool HasAnyBody(this BaseMethodDeclarationSyntax declaration) { return (declaration.Body ?? (SyntaxNode?)declaration.ExpressionBody) != null; } internal static bool IsTopLevelStatement([NotNullWhen(true)] GlobalStatementSyntax? syntax) { return syntax?.Parent?.IsKind(SyntaxKind.CompilationUnit) == true; } internal static bool IsSimpleProgramTopLevelStatement(GlobalStatementSyntax? syntax) { return IsTopLevelStatement(syntax) && syntax.SyntaxTree.Options.Kind == SourceCodeKind.Regular; } internal static bool HasAwaitOperations(SyntaxNode node) { // Do not descend into functions return node.DescendantNodesAndSelf(child => !IsNestedFunction(child)).Any( node => { switch (node) { case AwaitExpressionSyntax _: case LocalDeclarationStatementSyntax local when local.AwaitKeyword.IsKind(SyntaxKind.AwaitKeyword): case CommonForEachStatementSyntax @foreach when @foreach.AwaitKeyword.IsKind(SyntaxKind.AwaitKeyword): case UsingStatementSyntax @using when @using.AwaitKeyword.IsKind(SyntaxKind.AwaitKeyword): return true; default: return false; } }); } internal static bool IsNestedFunction(SyntaxNode child) { switch (child.Kind()) { case SyntaxKind.LocalFunctionStatement: case SyntaxKind.AnonymousMethodExpression: case SyntaxKind.SimpleLambdaExpression: case SyntaxKind.ParenthesizedLambdaExpression: return true; default: return false; } } internal static bool HasYieldOperations(SyntaxNode? node) { // Do not descend into functions and expressions return node is object && node.DescendantNodesAndSelf(child => { Debug.Assert(ReferenceEquals(node, child) || child is not (MemberDeclarationSyntax or TypeDeclarationSyntax)); return !IsNestedFunction(child) && !(node is ExpressionSyntax); }).Any(n => n is YieldStatementSyntax); } internal static bool HasReturnWithExpression(SyntaxNode? node) { // Do not descend into functions and expressions return node is object && node.DescendantNodesAndSelf(child => !IsNestedFunction(child) && !(node is ExpressionSyntax)).Any(n => n is ReturnStatementSyntax { Expression: { } }); } } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Rewriters/LocalDeclarationRewriter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.PooledObjects; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator { internal sealed class LocalDeclarationRewriter { internal static BoundStatement Rewrite( CSharpCompilation compilation, EENamedTypeSymbol container, HashSet<LocalSymbol> declaredLocals, BoundStatement node, ImmutableArray<LocalSymbol> declaredLocalsArray, DiagnosticBag diagnostics) { var builder = ArrayBuilder<BoundStatement>.GetInstance(); foreach (var local in declaredLocalsArray) { CreateLocal(compilation, declaredLocals, builder, local, node.Syntax, diagnostics); } // Rewrite top-level declarations only. switch (node.Kind) { case BoundKind.LocalDeclaration: Debug.Assert(declaredLocals.Contains(((BoundLocalDeclaration)node).LocalSymbol)); RewriteLocalDeclaration(builder, (BoundLocalDeclaration)node); break; case BoundKind.MultipleLocalDeclarations: foreach (var declaration in ((BoundMultipleLocalDeclarations)node).LocalDeclarations) { Debug.Assert(declaredLocals.Contains(declaration.LocalSymbol)); RewriteLocalDeclaration(builder, declaration); } break; default: if (builder.Count == 0) { builder.Free(); return node; } builder.Add(node); break; } return BoundBlock.SynthesizedNoLocals(node.Syntax, builder.ToImmutableAndFree()); } private static void RewriteLocalDeclaration( ArrayBuilder<BoundStatement> statements, BoundLocalDeclaration node) { Debug.Assert(node.ArgumentsOpt.IsDefault); var initializer = node.InitializerOpt; if (initializer != null) { var local = node.LocalSymbol; var syntax = node.Syntax; // Generate assignment to local. The assignment will // be rewritten in PlaceholderLocalRewriter. var type = local.Type; var assignment = new BoundAssignmentOperator( syntax, new BoundLocal(syntax, local, constantValueOpt: null, type: type), initializer, false, type); statements.Add(new BoundExpressionStatement(syntax, assignment)); } } private static void CreateLocal( CSharpCompilation compilation, HashSet<LocalSymbol> declaredLocals, ArrayBuilder<BoundStatement> statements, LocalSymbol local, SyntaxNode syntax, DiagnosticBag diagnostics) { // CreateVariable(Type type, string name) var method = PlaceholderLocalSymbol.GetIntrinsicMethod(compilation, ExpressionCompilerConstants.CreateVariableMethodName); if ((object)method == null) { diagnostics.Add(ErrorCode.ERR_DeclarationExpressionNotPermitted, local.Locations[0]); return; } declaredLocals.Add(local); var typeType = compilation.GetWellKnownType(WellKnownType.System_Type); var stringType = compilation.GetSpecialType(SpecialType.System_String); var guidConstructor = (MethodSymbol)compilation.GetWellKnownTypeMember(WellKnownMember.System_Guid__ctor); var type = new BoundTypeOfOperator(syntax, new BoundTypeExpression(syntax, aliasOpt: null, type: local.Type), null, typeType); var name = new BoundLiteral(syntax, ConstantValue.Create(local.Name), stringType); bool hasCustomTypeInfoPayload; var customTypeInfoPayload = GetCustomTypeInfoPayload(local, syntax, compilation, out hasCustomTypeInfoPayload); var customTypeInfoPayloadId = GetCustomTypeInfoPayloadId(syntax, guidConstructor, hasCustomTypeInfoPayload); var call = BoundCall.Synthesized( syntax, receiverOpt: null, method: method, arguments: ImmutableArray.Create(type, name, customTypeInfoPayloadId, customTypeInfoPayload)); statements.Add(new BoundExpressionStatement(syntax, call)); } private static BoundExpression GetCustomTypeInfoPayloadId(SyntaxNode syntax, MethodSymbol guidConstructor, bool hasCustomTypeInfoPayload) { if (!hasCustomTypeInfoPayload) { return new BoundDefaultExpression(syntax, targetType: null, constantValueOpt: null, guidConstructor.ContainingType); } var value = ConstantValue.Create(CustomTypeInfo.PayloadTypeId.ToString()); return new BoundObjectCreationExpression( syntax, guidConstructor, new BoundLiteral(syntax, value, guidConstructor.ContainingType)); } private static BoundExpression GetCustomTypeInfoPayload(LocalSymbol local, SyntaxNode syntax, CSharpCompilation compilation, out bool hasCustomTypeInfoPayload) { var byteArrayType = ArrayTypeSymbol.CreateSZArray( compilation.Assembly, TypeWithAnnotations.Create(compilation.GetSpecialType(SpecialType.System_Byte))); var bytes = compilation.GetCustomTypeInfoPayload(local.Type, customModifiersCount: 0, refKind: RefKind.None); hasCustomTypeInfoPayload = bytes != null; if (!hasCustomTypeInfoPayload) { return new BoundLiteral(syntax, ConstantValue.Null, byteArrayType); } var byteType = byteArrayType.ElementType; var intType = compilation.GetSpecialType(SpecialType.System_Int32); var numBytes = bytes.Count; var initializerExprs = ArrayBuilder<BoundExpression>.GetInstance(numBytes); foreach (var b in bytes) { initializerExprs.Add(new BoundLiteral(syntax, ConstantValue.Create(b), byteType)); } var lengthExpr = new BoundLiteral(syntax, ConstantValue.Create(numBytes), intType); return new BoundArrayCreation( syntax, ImmutableArray.Create<BoundExpression>(lengthExpr), new BoundArrayInitialization(syntax, initializerExprs.ToImmutableAndFree()), byteArrayType); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.PooledObjects; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator { internal sealed class LocalDeclarationRewriter { internal static BoundStatement Rewrite( CSharpCompilation compilation, EENamedTypeSymbol container, HashSet<LocalSymbol> declaredLocals, BoundStatement node, ImmutableArray<LocalSymbol> declaredLocalsArray, DiagnosticBag diagnostics) { var builder = ArrayBuilder<BoundStatement>.GetInstance(); foreach (var local in declaredLocalsArray) { CreateLocal(compilation, declaredLocals, builder, local, node.Syntax, diagnostics); } // Rewrite top-level declarations only. switch (node.Kind) { case BoundKind.LocalDeclaration: Debug.Assert(declaredLocals.Contains(((BoundLocalDeclaration)node).LocalSymbol)); RewriteLocalDeclaration(builder, (BoundLocalDeclaration)node); break; case BoundKind.MultipleLocalDeclarations: foreach (var declaration in ((BoundMultipleLocalDeclarations)node).LocalDeclarations) { Debug.Assert(declaredLocals.Contains(declaration.LocalSymbol)); RewriteLocalDeclaration(builder, declaration); } break; default: if (builder.Count == 0) { builder.Free(); return node; } builder.Add(node); break; } return BoundBlock.SynthesizedNoLocals(node.Syntax, builder.ToImmutableAndFree()); } private static void RewriteLocalDeclaration( ArrayBuilder<BoundStatement> statements, BoundLocalDeclaration node) { Debug.Assert(node.ArgumentsOpt.IsDefault); var initializer = node.InitializerOpt; if (initializer != null) { var local = node.LocalSymbol; var syntax = node.Syntax; // Generate assignment to local. The assignment will // be rewritten in PlaceholderLocalRewriter. var type = local.Type; var assignment = new BoundAssignmentOperator( syntax, new BoundLocal(syntax, local, constantValueOpt: null, type: type), initializer, false, type); statements.Add(new BoundExpressionStatement(syntax, assignment)); } } private static void CreateLocal( CSharpCompilation compilation, HashSet<LocalSymbol> declaredLocals, ArrayBuilder<BoundStatement> statements, LocalSymbol local, SyntaxNode syntax, DiagnosticBag diagnostics) { // CreateVariable(Type type, string name) var method = PlaceholderLocalSymbol.GetIntrinsicMethod(compilation, ExpressionCompilerConstants.CreateVariableMethodName); if ((object)method == null) { diagnostics.Add(ErrorCode.ERR_DeclarationExpressionNotPermitted, local.Locations[0]); return; } declaredLocals.Add(local); var typeType = compilation.GetWellKnownType(WellKnownType.System_Type); var stringType = compilation.GetSpecialType(SpecialType.System_String); var guidConstructor = (MethodSymbol)compilation.GetWellKnownTypeMember(WellKnownMember.System_Guid__ctor); var type = new BoundTypeOfOperator(syntax, new BoundTypeExpression(syntax, aliasOpt: null, type: local.Type), null, typeType); var name = new BoundLiteral(syntax, ConstantValue.Create(local.Name), stringType); bool hasCustomTypeInfoPayload; var customTypeInfoPayload = GetCustomTypeInfoPayload(local, syntax, compilation, out hasCustomTypeInfoPayload); var customTypeInfoPayloadId = GetCustomTypeInfoPayloadId(syntax, guidConstructor, hasCustomTypeInfoPayload); var call = BoundCall.Synthesized( syntax, receiverOpt: null, method: method, arguments: ImmutableArray.Create(type, name, customTypeInfoPayloadId, customTypeInfoPayload)); statements.Add(new BoundExpressionStatement(syntax, call)); } private static BoundExpression GetCustomTypeInfoPayloadId(SyntaxNode syntax, MethodSymbol guidConstructor, bool hasCustomTypeInfoPayload) { if (!hasCustomTypeInfoPayload) { return new BoundDefaultExpression(syntax, targetType: null, constantValueOpt: null, guidConstructor.ContainingType); } var value = ConstantValue.Create(CustomTypeInfo.PayloadTypeId.ToString()); return new BoundObjectCreationExpression( syntax, guidConstructor, new BoundLiteral(syntax, value, guidConstructor.ContainingType)); } private static BoundExpression GetCustomTypeInfoPayload(LocalSymbol local, SyntaxNode syntax, CSharpCompilation compilation, out bool hasCustomTypeInfoPayload) { var byteArrayType = ArrayTypeSymbol.CreateSZArray( compilation.Assembly, TypeWithAnnotations.Create(compilation.GetSpecialType(SpecialType.System_Byte))); var bytes = compilation.GetCustomTypeInfoPayload(local.Type, customModifiersCount: 0, refKind: RefKind.None); hasCustomTypeInfoPayload = bytes != null; if (!hasCustomTypeInfoPayload) { return new BoundLiteral(syntax, ConstantValue.Null, byteArrayType); } var byteType = byteArrayType.ElementType; var intType = compilation.GetSpecialType(SpecialType.System_Int32); var numBytes = bytes.Count; var initializerExprs = ArrayBuilder<BoundExpression>.GetInstance(numBytes); foreach (var b in bytes) { initializerExprs.Add(new BoundLiteral(syntax, ConstantValue.Create(b), byteType)); } var lengthExpr = new BoundLiteral(syntax, ConstantValue.Create(numBytes), intType); return new BoundArrayCreation( syntax, ImmutableArray.Create<BoundExpression>(lengthExpr), new BoundArrayInitialization(syntax, initializerExprs.ToImmutableAndFree()), byteArrayType); } } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/VisualStudio/Xaml/Impl/Features/AutoInsert/XamlAutoInsertResult.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Text; namespace Microsoft.VisualStudio.LanguageServices.Xaml.Features.AutoInsert { internal class XamlAutoInsertResult { public TextChange TextChange { get; set; } public int? CaretOffset { get; set; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Text; namespace Microsoft.VisualStudio.LanguageServices.Xaml.Features.AutoInsert { internal class XamlAutoInsertResult { public TextChange TextChange { get; set; } public int? CaretOffset { get; set; } } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/VisualStudio/VisualStudioDiagnosticsToolWindow/PkgCmdID.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Roslyn.VisualStudio.DiagnosticsWindow { internal static class PkgCmdIDList { public const uint CmdIDRoslynDiagnosticWindow = 0x101; }; }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Roslyn.VisualStudio.DiagnosticsWindow { internal static class PkgCmdIDList { public const uint CmdIDRoslynDiagnosticWindow = 0x101; }; }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/Features/Core/Portable/Workspace/BackgroundParser.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.SolutionCrawler; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Host { /// <summary> /// when users type, we chain all those changes as incremental parsing requests /// but doesn't actually realize those changes. it is saved as a pending request. /// so if nobody asks for final parse tree, those chain can keep grow. /// we do this since Roslyn is lazy at the core (don't do work if nobody asks for it) /// /// but certain host such as VS, we have this (BackgroundParser) which preemptively /// trying to realize such trees for open/active files expecting users will use them soonish. /// </summary> internal sealed class BackgroundParser { private readonly Workspace _workspace; private readonly TaskQueue _taskQueue; private readonly IDocumentTrackingService _documentTrackingService; private readonly ReaderWriterLockSlim _stateLock = new(LockRecursionPolicy.NoRecursion); private readonly object _parseGate = new(); private ImmutableDictionary<DocumentId, CancellationTokenSource> _workMap = ImmutableDictionary.Create<DocumentId, CancellationTokenSource>(); public bool IsStarted { get; private set; } public BackgroundParser(Workspace workspace) { _workspace = workspace; var listenerProvider = workspace.Services.GetRequiredService<IWorkspaceAsynchronousOperationListenerProvider>(); _taskQueue = new TaskQueue(listenerProvider.GetListener(), TaskScheduler.Default); _documentTrackingService = workspace.Services.GetRequiredService<IDocumentTrackingService>(); _documentTrackingService.ActiveDocumentChanged += OnActiveDocumentChanged; _workspace.WorkspaceChanged += OnWorkspaceChanged; workspace.DocumentOpened += OnDocumentOpened; workspace.DocumentClosed += OnDocumentClosed; } private void OnActiveDocumentChanged(object sender, DocumentId activeDocumentId) => Parse(_workspace.CurrentSolution.GetDocument(activeDocumentId)); private void OnDocumentOpened(object sender, DocumentEventArgs args) => Parse(args.Document); private void OnDocumentClosed(object sender, DocumentEventArgs args) => CancelParse(args.Document.Id); private void OnWorkspaceChanged(object sender, WorkspaceChangeEventArgs args) { switch (args.Kind) { case WorkspaceChangeKind.SolutionCleared: case WorkspaceChangeKind.SolutionRemoved: case WorkspaceChangeKind.SolutionAdded: CancelAllParses(); break; case WorkspaceChangeKind.DocumentRemoved: CancelParse(args.DocumentId); break; case WorkspaceChangeKind.DocumentChanged: ParseIfOpen(args.NewSolution.GetDocument(args.DocumentId)); break; case WorkspaceChangeKind.ProjectChanged: var oldProject = args.OldSolution.GetProject(args.ProjectId); var newProject = args.NewSolution.GetProject(args.ProjectId); // Perf optimization: don't rescan the new project if parse options didn't change. When looking // at the perf of changing configurations that resulted in many reference additions/removals, // this consumed around 2%-3% of the trace after some other optimizations I did. Most of that // was actually walking the documents list since this was causing all the Documents to be realized. // Since this is on the UI thread, it's best just to not do the work if we don't need it. if (oldProject.SupportsCompilation && !object.Equals(oldProject.ParseOptions, newProject.ParseOptions)) { foreach (var doc in newProject.Documents) { ParseIfOpen(doc); } } break; } } public void Start() { using (_stateLock.DisposableRead()) { if (!IsStarted) { IsStarted = true; } } } public void Stop() { using (_stateLock.DisposableWrite()) { if (IsStarted) { CancelAllParses_NoLock(); IsStarted = false; } } } public void CancelAllParses() { using (_stateLock.DisposableWrite()) { CancelAllParses_NoLock(); } } private void CancelAllParses_NoLock() { _stateLock.AssertCanWrite(); foreach (var tuple in _workMap) { tuple.Value.Cancel(); } _workMap = ImmutableDictionary.Create<DocumentId, CancellationTokenSource>(); } public void CancelParse(DocumentId documentId) { if (documentId != null) { using (_stateLock.DisposableWrite()) { if (_workMap.TryGetValue(documentId, out var cancellationTokenSource)) { cancellationTokenSource.Cancel(); _workMap = _workMap.Remove(documentId); } } } } public void Parse(Document document) { if (document != null) { lock (_parseGate) { CancelParse(document.Id); if (IsStarted) { _ = ParseDocumentAsync(document); } } } } private void ParseIfOpen(Document document) { if (document != null && document.IsOpen()) { Parse(document); } } private Task ParseDocumentAsync(Document document) { var cancellationTokenSource = new CancellationTokenSource(); using (_stateLock.DisposableWrite()) { _workMap = _workMap.Add(document.Id, cancellationTokenSource); } var cancellationToken = cancellationTokenSource.Token; // We end up creating a chain of parsing tasks that each attempt to produce // the appropriate syntax tree for any given document. Once we start work to create // the syntax tree for a given document, we don't want to stop. // Otherwise we can end up in the unfortunate scenario where we keep cancelling work, // and then having the next task re-do the work we were just in the middle of. // By not cancelling, we can reuse the useful results of previous tasks when performing later steps in the chain. // // we still cancel whole task if the task didn't start yet. we just don't cancel if task is started but not finished yet. return _taskQueue.ScheduleTask( "BackgroundParser.ParseDocumentAsync", async () => { try { if (SolutionCrawlerOptions.GetBackgroundAnalysisScope(document.Project) == BackgroundAnalysisScope.ActiveFile && _documentTrackingService?.TryGetActiveDocument() != document.Id) { // Active file analysis is enabled, but the document for parsing is not the current // document. Return immediately without parsing. return; } await document.GetSyntaxTreeAsync(CancellationToken.None).ConfigureAwait(false); } finally { // Always ensure that we mark this work as done from the workmap. using (_stateLock.DisposableWrite()) { // Check that we are still the active parse in the workmap before we remove it. // Concievably if this continuation got delayed and another parse was put in, we might // end up removing the tracking for another in-flight task. if (_workMap.TryGetValue(document.Id, out var sourceInMap) && sourceInMap == cancellationTokenSource) { _workMap = _workMap.Remove(document.Id); } } } }, cancellationToken); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.SolutionCrawler; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Host { /// <summary> /// when users type, we chain all those changes as incremental parsing requests /// but doesn't actually realize those changes. it is saved as a pending request. /// so if nobody asks for final parse tree, those chain can keep grow. /// we do this since Roslyn is lazy at the core (don't do work if nobody asks for it) /// /// but certain host such as VS, we have this (BackgroundParser) which preemptively /// trying to realize such trees for open/active files expecting users will use them soonish. /// </summary> internal sealed class BackgroundParser { private readonly Workspace _workspace; private readonly TaskQueue _taskQueue; private readonly IDocumentTrackingService _documentTrackingService; private readonly ReaderWriterLockSlim _stateLock = new(LockRecursionPolicy.NoRecursion); private readonly object _parseGate = new(); private ImmutableDictionary<DocumentId, CancellationTokenSource> _workMap = ImmutableDictionary.Create<DocumentId, CancellationTokenSource>(); public bool IsStarted { get; private set; } public BackgroundParser(Workspace workspace) { _workspace = workspace; var listenerProvider = workspace.Services.GetRequiredService<IWorkspaceAsynchronousOperationListenerProvider>(); _taskQueue = new TaskQueue(listenerProvider.GetListener(), TaskScheduler.Default); _documentTrackingService = workspace.Services.GetRequiredService<IDocumentTrackingService>(); _documentTrackingService.ActiveDocumentChanged += OnActiveDocumentChanged; _workspace.WorkspaceChanged += OnWorkspaceChanged; workspace.DocumentOpened += OnDocumentOpened; workspace.DocumentClosed += OnDocumentClosed; } private void OnActiveDocumentChanged(object sender, DocumentId activeDocumentId) => Parse(_workspace.CurrentSolution.GetDocument(activeDocumentId)); private void OnDocumentOpened(object sender, DocumentEventArgs args) => Parse(args.Document); private void OnDocumentClosed(object sender, DocumentEventArgs args) => CancelParse(args.Document.Id); private void OnWorkspaceChanged(object sender, WorkspaceChangeEventArgs args) { switch (args.Kind) { case WorkspaceChangeKind.SolutionCleared: case WorkspaceChangeKind.SolutionRemoved: case WorkspaceChangeKind.SolutionAdded: CancelAllParses(); break; case WorkspaceChangeKind.DocumentRemoved: CancelParse(args.DocumentId); break; case WorkspaceChangeKind.DocumentChanged: ParseIfOpen(args.NewSolution.GetDocument(args.DocumentId)); break; case WorkspaceChangeKind.ProjectChanged: var oldProject = args.OldSolution.GetProject(args.ProjectId); var newProject = args.NewSolution.GetProject(args.ProjectId); // Perf optimization: don't rescan the new project if parse options didn't change. When looking // at the perf of changing configurations that resulted in many reference additions/removals, // this consumed around 2%-3% of the trace after some other optimizations I did. Most of that // was actually walking the documents list since this was causing all the Documents to be realized. // Since this is on the UI thread, it's best just to not do the work if we don't need it. if (oldProject.SupportsCompilation && !object.Equals(oldProject.ParseOptions, newProject.ParseOptions)) { foreach (var doc in newProject.Documents) { ParseIfOpen(doc); } } break; } } public void Start() { using (_stateLock.DisposableRead()) { if (!IsStarted) { IsStarted = true; } } } public void Stop() { using (_stateLock.DisposableWrite()) { if (IsStarted) { CancelAllParses_NoLock(); IsStarted = false; } } } public void CancelAllParses() { using (_stateLock.DisposableWrite()) { CancelAllParses_NoLock(); } } private void CancelAllParses_NoLock() { _stateLock.AssertCanWrite(); foreach (var tuple in _workMap) { tuple.Value.Cancel(); } _workMap = ImmutableDictionary.Create<DocumentId, CancellationTokenSource>(); } public void CancelParse(DocumentId documentId) { if (documentId != null) { using (_stateLock.DisposableWrite()) { if (_workMap.TryGetValue(documentId, out var cancellationTokenSource)) { cancellationTokenSource.Cancel(); _workMap = _workMap.Remove(documentId); } } } } public void Parse(Document document) { if (document != null) { lock (_parseGate) { CancelParse(document.Id); if (IsStarted) { _ = ParseDocumentAsync(document); } } } } private void ParseIfOpen(Document document) { if (document != null && document.IsOpen()) { Parse(document); } } private Task ParseDocumentAsync(Document document) { var cancellationTokenSource = new CancellationTokenSource(); using (_stateLock.DisposableWrite()) { _workMap = _workMap.Add(document.Id, cancellationTokenSource); } var cancellationToken = cancellationTokenSource.Token; // We end up creating a chain of parsing tasks that each attempt to produce // the appropriate syntax tree for any given document. Once we start work to create // the syntax tree for a given document, we don't want to stop. // Otherwise we can end up in the unfortunate scenario where we keep cancelling work, // and then having the next task re-do the work we were just in the middle of. // By not cancelling, we can reuse the useful results of previous tasks when performing later steps in the chain. // // we still cancel whole task if the task didn't start yet. we just don't cancel if task is started but not finished yet. return _taskQueue.ScheduleTask( "BackgroundParser.ParseDocumentAsync", async () => { try { if (SolutionCrawlerOptions.GetBackgroundAnalysisScope(document.Project) == BackgroundAnalysisScope.ActiveFile && _documentTrackingService?.TryGetActiveDocument() != document.Id) { // Active file analysis is enabled, but the document for parsing is not the current // document. Return immediately without parsing. return; } await document.GetSyntaxTreeAsync(CancellationToken.None).ConfigureAwait(false); } finally { // Always ensure that we mark this work as done from the workmap. using (_stateLock.DisposableWrite()) { // Check that we are still the active parse in the workmap before we remove it. // Concievably if this continuation got delayed and another parse was put in, we might // end up removing the tracking for another in-flight task. if (_workMap.TryGetValue(document.Id, out var sourceInMap) && sourceInMap == cancellationTokenSource) { _workMap = _workMap.Remove(document.Id); } } } }, cancellationToken); } } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/VisualStudio/Core/Impl/Options/Style/NamingPreferences/SymbolSpecification/SymbolSpecificationDialog.xaml.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using System.Windows; using System.Windows.Automation; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Input; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Microsoft.VisualStudio.PlatformUI; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options.Style.NamingPreferences { internal partial class SymbolSpecificationDialog : DialogWindow { private readonly SymbolSpecificationViewModel _viewModel; public string DialogTitle => ServicesVSResources.Symbol_Specification; public string SymbolSpecificationTitleLabelText => ServicesVSResources.Symbol_Specification_Title_colon; public string SymbolKindsLabelText => ServicesVSResources.Symbol_Kinds_can_match_any; public string AccessibilitiesLabelText => ServicesVSResources.Accessibilities_can_match_any; public string ModifiersLabelText => ServicesVSResources.Modifiers_must_match_all; public string SelectAllButtonText => ServicesVSResources.Select_All; public string DeselectAllButtonText => ServicesVSResources.Deselect_All; public string OK => ServicesVSResources.OK; public string Cancel => ServicesVSResources.Cancel; private readonly AutomationDelegatingListView symbolKindsListView; private readonly AutomationDelegatingListView accessibilitiesListView; private readonly AutomationDelegatingListView modifiersListView; internal SymbolSpecificationDialog(SymbolSpecificationViewModel viewModel) { _viewModel = viewModel; InitializeComponent(); DataContext = viewModel; // AutomationDelegatingListView is defined in ServicesVisualStudio, which has // InternalsVisibleTo this project. But, the markup compiler doesn't consider the IVT // relationship, so declaring the AutomationDelegatingListView in XAML would require // duplicating that type in this project. Declaring and setting it here avoids the // markup compiler completely, allowing us to reference the internal // AutomationDelegatingListView without issue. symbolKindsListView = CreateAutomationDelegatingListView(nameof(SymbolSpecificationViewModel.SymbolKindList)); symbolKindsContentControl.Content = symbolKindsListView; accessibilitiesListView = CreateAutomationDelegatingListView(nameof(SymbolSpecificationViewModel.AccessibilityList)); accessibilitiesContentControl.Content = accessibilitiesListView; modifiersListView = CreateAutomationDelegatingListView(nameof(SymbolSpecificationViewModel.ModifierList)); modifiersContentControl.Content = modifiersListView; symbolKindsListView.AddHandler(PreviewKeyDownEvent, (KeyEventHandler)HandleSymbolKindsPreviewKeyDown, true); accessibilitiesListView.AddHandler(PreviewKeyDownEvent, (KeyEventHandler)HandleAccessibilitiesPreviewKeyDown, true); modifiersListView.AddHandler(PreviewKeyDownEvent, (KeyEventHandler)HandleModifiersPreviewKeyDown, true); } private AutomationDelegatingListView CreateAutomationDelegatingListView(string itemsSourceName) { var listView = new AutomationDelegatingListView(); listView.SelectionMode = SelectionMode.Extended; listView.SetBinding(ItemsControl.ItemsSourceProperty, new Binding(itemsSourceName)); listView.SetResourceReference(ItemsControl.ItemTemplateProperty, "listViewDataTemplate"); return listView; } private void HandleSymbolKindsPreviewKeyDown(object sender, KeyEventArgs e) => HandlePreviewKeyDown(e, symbolKindsListView.SelectedItems.OfType<SymbolSpecificationViewModel.SymbolKindViewModel>()); private void HandleAccessibilitiesPreviewKeyDown(object sender, KeyEventArgs e) => HandlePreviewKeyDown(e, accessibilitiesListView.SelectedItems.OfType<SymbolSpecificationViewModel.AccessibilityViewModel>()); private void HandleModifiersPreviewKeyDown(object sender, KeyEventArgs e) => HandlePreviewKeyDown(e, modifiersListView.SelectedItems.OfType<SymbolSpecificationViewModel.ModifierViewModel>()); private void HandlePreviewKeyDown<T>(KeyEventArgs e, IEnumerable<T> selectedItems) where T : SymbolSpecificationViewModel.ISymbolSpecificationViewModelPart { if (e.Key == Key.Space) { e.Handled = true; var targetCheckedState = !selectedItems.All(d => d.IsChecked); foreach (var item in selectedItems) { item.IsChecked = targetCheckedState; } } } private void SelectAllSymbolKinds(object sender, RoutedEventArgs e) { foreach (var item in symbolKindsListView.Items.OfType<SymbolSpecificationViewModel.SymbolKindViewModel>()) { item.IsChecked = true; } } private void DeselectAllSymbolKinds(object sender, RoutedEventArgs e) { foreach (var item in symbolKindsListView.Items.OfType<SymbolSpecificationViewModel.SymbolKindViewModel>()) { item.IsChecked = false; } } private void SelectAllAccessibilities(object sender, RoutedEventArgs e) { foreach (var item in accessibilitiesListView.Items.OfType<SymbolSpecificationViewModel.AccessibilityViewModel>()) { item.IsChecked = true; } } private void DeselectAllAccessibilities(object sender, RoutedEventArgs e) { foreach (var item in accessibilitiesListView.Items.OfType<SymbolSpecificationViewModel.AccessibilityViewModel>()) { item.IsChecked = false; } } private void SelectAllModifiers(object sender, RoutedEventArgs e) { foreach (var item in modifiersListView.Items.OfType<SymbolSpecificationViewModel.ModifierViewModel>()) { item.IsChecked = true; } } private void DeselectAllModifiers(object sender, RoutedEventArgs e) { foreach (var item in modifiersListView.Items.OfType<SymbolSpecificationViewModel.ModifierViewModel>()) { item.IsChecked = false; } } private void OK_Click(object sender, RoutedEventArgs e) { if (_viewModel.TrySubmit()) { DialogResult = true; } } private void Cancel_Click(object sender, RoutedEventArgs e) => DialogResult = false; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using System.Windows; using System.Windows.Automation; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Input; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Microsoft.VisualStudio.PlatformUI; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options.Style.NamingPreferences { internal partial class SymbolSpecificationDialog : DialogWindow { private readonly SymbolSpecificationViewModel _viewModel; public string DialogTitle => ServicesVSResources.Symbol_Specification; public string SymbolSpecificationTitleLabelText => ServicesVSResources.Symbol_Specification_Title_colon; public string SymbolKindsLabelText => ServicesVSResources.Symbol_Kinds_can_match_any; public string AccessibilitiesLabelText => ServicesVSResources.Accessibilities_can_match_any; public string ModifiersLabelText => ServicesVSResources.Modifiers_must_match_all; public string SelectAllButtonText => ServicesVSResources.Select_All; public string DeselectAllButtonText => ServicesVSResources.Deselect_All; public string OK => ServicesVSResources.OK; public string Cancel => ServicesVSResources.Cancel; private readonly AutomationDelegatingListView symbolKindsListView; private readonly AutomationDelegatingListView accessibilitiesListView; private readonly AutomationDelegatingListView modifiersListView; internal SymbolSpecificationDialog(SymbolSpecificationViewModel viewModel) { _viewModel = viewModel; InitializeComponent(); DataContext = viewModel; // AutomationDelegatingListView is defined in ServicesVisualStudio, which has // InternalsVisibleTo this project. But, the markup compiler doesn't consider the IVT // relationship, so declaring the AutomationDelegatingListView in XAML would require // duplicating that type in this project. Declaring and setting it here avoids the // markup compiler completely, allowing us to reference the internal // AutomationDelegatingListView without issue. symbolKindsListView = CreateAutomationDelegatingListView(nameof(SymbolSpecificationViewModel.SymbolKindList)); symbolKindsContentControl.Content = symbolKindsListView; accessibilitiesListView = CreateAutomationDelegatingListView(nameof(SymbolSpecificationViewModel.AccessibilityList)); accessibilitiesContentControl.Content = accessibilitiesListView; modifiersListView = CreateAutomationDelegatingListView(nameof(SymbolSpecificationViewModel.ModifierList)); modifiersContentControl.Content = modifiersListView; symbolKindsListView.AddHandler(PreviewKeyDownEvent, (KeyEventHandler)HandleSymbolKindsPreviewKeyDown, true); accessibilitiesListView.AddHandler(PreviewKeyDownEvent, (KeyEventHandler)HandleAccessibilitiesPreviewKeyDown, true); modifiersListView.AddHandler(PreviewKeyDownEvent, (KeyEventHandler)HandleModifiersPreviewKeyDown, true); } private AutomationDelegatingListView CreateAutomationDelegatingListView(string itemsSourceName) { var listView = new AutomationDelegatingListView(); listView.SelectionMode = SelectionMode.Extended; listView.SetBinding(ItemsControl.ItemsSourceProperty, new Binding(itemsSourceName)); listView.SetResourceReference(ItemsControl.ItemTemplateProperty, "listViewDataTemplate"); return listView; } private void HandleSymbolKindsPreviewKeyDown(object sender, KeyEventArgs e) => HandlePreviewKeyDown(e, symbolKindsListView.SelectedItems.OfType<SymbolSpecificationViewModel.SymbolKindViewModel>()); private void HandleAccessibilitiesPreviewKeyDown(object sender, KeyEventArgs e) => HandlePreviewKeyDown(e, accessibilitiesListView.SelectedItems.OfType<SymbolSpecificationViewModel.AccessibilityViewModel>()); private void HandleModifiersPreviewKeyDown(object sender, KeyEventArgs e) => HandlePreviewKeyDown(e, modifiersListView.SelectedItems.OfType<SymbolSpecificationViewModel.ModifierViewModel>()); private void HandlePreviewKeyDown<T>(KeyEventArgs e, IEnumerable<T> selectedItems) where T : SymbolSpecificationViewModel.ISymbolSpecificationViewModelPart { if (e.Key == Key.Space) { e.Handled = true; var targetCheckedState = !selectedItems.All(d => d.IsChecked); foreach (var item in selectedItems) { item.IsChecked = targetCheckedState; } } } private void SelectAllSymbolKinds(object sender, RoutedEventArgs e) { foreach (var item in symbolKindsListView.Items.OfType<SymbolSpecificationViewModel.SymbolKindViewModel>()) { item.IsChecked = true; } } private void DeselectAllSymbolKinds(object sender, RoutedEventArgs e) { foreach (var item in symbolKindsListView.Items.OfType<SymbolSpecificationViewModel.SymbolKindViewModel>()) { item.IsChecked = false; } } private void SelectAllAccessibilities(object sender, RoutedEventArgs e) { foreach (var item in accessibilitiesListView.Items.OfType<SymbolSpecificationViewModel.AccessibilityViewModel>()) { item.IsChecked = true; } } private void DeselectAllAccessibilities(object sender, RoutedEventArgs e) { foreach (var item in accessibilitiesListView.Items.OfType<SymbolSpecificationViewModel.AccessibilityViewModel>()) { item.IsChecked = false; } } private void SelectAllModifiers(object sender, RoutedEventArgs e) { foreach (var item in modifiersListView.Items.OfType<SymbolSpecificationViewModel.ModifierViewModel>()) { item.IsChecked = true; } } private void DeselectAllModifiers(object sender, RoutedEventArgs e) { foreach (var item in modifiersListView.Items.OfType<SymbolSpecificationViewModel.ModifierViewModel>()) { item.IsChecked = false; } } private void OK_Click(object sender, RoutedEventArgs e) { if (_viewModel.TrySubmit()) { DialogResult = true; } } private void Cancel_Click(object sender, RoutedEventArgs e) => DialogResult = false; } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/Compilers/CSharp/Portable/Lowering/ClosureConversion/ClosureKind.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.CodeAnalysis.CSharp { internal enum ClosureKind { /// <summary> /// The closure doesn't declare any variables, and is never converted to a delegate. /// Lambdas are emitted directly to the containing class as a static method. /// </summary> Static, /// <summary> /// The closure doesn't declare any variables, and is converted to a delegate at least once. /// Display class is a singleton and may be shared with other top-level methods. /// </summary> Singleton, /// <summary> /// The closure only contains a reference to the containing class instance ("this"). /// We don't emit a display class, lambdas are emitted directly to the containing class as its instance methods. /// </summary> ThisOnly, /// <summary> /// General closure. /// Display class may only contain lambdas defined in the same top-level method. /// </summary> General, } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.CodeAnalysis.CSharp { internal enum ClosureKind { /// <summary> /// The closure doesn't declare any variables, and is never converted to a delegate. /// Lambdas are emitted directly to the containing class as a static method. /// </summary> Static, /// <summary> /// The closure doesn't declare any variables, and is converted to a delegate at least once. /// Display class is a singleton and may be shared with other top-level methods. /// </summary> Singleton, /// <summary> /// The closure only contains a reference to the containing class instance ("this"). /// We don't emit a display class, lambdas are emitted directly to the containing class as its instance methods. /// </summary> ThisOnly, /// <summary> /// General closure. /// Display class may only contain lambdas defined in the same top-level method. /// </summary> General, } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/Compilers/Core/CodeAnalysisTest/Collections/List/SegmentedList.Generic.Tests.ConvertAll.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // NOTE: This code is derived from an implementation originally in dotnet/runtime: // https://github.com/dotnet/runtime/blob/v5.0.2/src/libraries/System.Collections/tests/Generic/List/List.Generic.Tests.ConvertAll.cs // // See the commentary in https://github.com/dotnet/roslyn/pull/50156 for notes on incorporating changes made to the // reference implementation. using System.Linq; using Microsoft.CodeAnalysis.Collections; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.Collections { public abstract partial class SegmentedList_Generic_Tests<T> : IList_Generic_Tests<T> { [Fact] public void ConvertAll() { var list = new SegmentedList<int>(new int[] { 1, 2, 3 }); var before = list.ToSegmentedList(); var after = list.ConvertAll((i) => { return 10 * i; }); Assert.Equal(before.Count, list.Count); Assert.Equal(before.Count, after.Count); for (int i = 0; i < list.Count; i++) { Assert.Equal(before[i], list[i]); Assert.Equal(before[i] * 10, after[i]); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // NOTE: This code is derived from an implementation originally in dotnet/runtime: // https://github.com/dotnet/runtime/blob/v5.0.2/src/libraries/System.Collections/tests/Generic/List/List.Generic.Tests.ConvertAll.cs // // See the commentary in https://github.com/dotnet/roslyn/pull/50156 for notes on incorporating changes made to the // reference implementation. using System.Linq; using Microsoft.CodeAnalysis.Collections; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.Collections { public abstract partial class SegmentedList_Generic_Tests<T> : IList_Generic_Tests<T> { [Fact] public void ConvertAll() { var list = new SegmentedList<int>(new int[] { 1, 2, 3 }); var before = list.ToSegmentedList(); var after = list.ConvertAll((i) => { return 10 * i; }); Assert.Equal(before.Count, list.Count); Assert.Equal(before.Count, after.Count); for (int i = 0; i < list.Count; i++) { Assert.Equal(before[i], list[i]); Assert.Equal(before[i] * 10, after[i]); } } } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Editing/GenerationOptions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.Editing { internal class GenerationOptions { public static readonly PerLanguageOption2<bool> PlaceSystemNamespaceFirst = new(nameof(GenerationOptions), CodeStyleOptionGroups.Usings, nameof(PlaceSystemNamespaceFirst), defaultValue: true, EditorConfigStorageLocation.ForBoolOption("dotnet_sort_system_directives_first"), new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.PlaceSystemNamespaceFirst")); public static readonly PerLanguageOption2<bool> SeparateImportDirectiveGroups = new( nameof(GenerationOptions), CodeStyleOptionGroups.Usings, nameof(SeparateImportDirectiveGroups), defaultValue: false, EditorConfigStorageLocation.ForBoolOption("dotnet_separate_import_directive_groups"), new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{nameof(SeparateImportDirectiveGroups)}")); public static readonly ImmutableArray<IOption2> AllOptions = ImmutableArray.Create<IOption2>( PlaceSystemNamespaceFirst, SeparateImportDirectiveGroups); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.Editing { internal class GenerationOptions { public static readonly PerLanguageOption2<bool> PlaceSystemNamespaceFirst = new(nameof(GenerationOptions), CodeStyleOptionGroups.Usings, nameof(PlaceSystemNamespaceFirst), defaultValue: true, EditorConfigStorageLocation.ForBoolOption("dotnet_sort_system_directives_first"), new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.PlaceSystemNamespaceFirst")); public static readonly PerLanguageOption2<bool> SeparateImportDirectiveGroups = new( nameof(GenerationOptions), CodeStyleOptionGroups.Usings, nameof(SeparateImportDirectiveGroups), defaultValue: false, EditorConfigStorageLocation.ForBoolOption("dotnet_separate_import_directive_groups"), new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{nameof(SeparateImportDirectiveGroups)}")); public static readonly ImmutableArray<IOption2> AllOptions = ImmutableArray.Create<IOption2>( PlaceSystemNamespaceFirst, SeparateImportDirectiveGroups); } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/Workspaces/Core/MSBuild/MSBuild/VisualBasic/VisualBasicCommandLineArgumentReader.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using Microsoft.CodeAnalysis.MSBuild; using Roslyn.Utilities; using MSB = Microsoft.Build; namespace Microsoft.CodeAnalysis.VisualBasic { internal class VisualBasicCommandLineArgumentReader : CommandLineArgumentReader { public VisualBasicCommandLineArgumentReader(MSB.Execution.ProjectInstance project) : base(project) { } public static ImmutableArray<string> Read(MSB.Execution.ProjectInstance project) { return new VisualBasicCommandLineArgumentReader(project).Read(); } protected override void ReadCore() { ReadAdditionalFiles(); ReadAnalyzers(); ReadCodePage(); ReadDebugInfo(); ReadDelaySign(); ReadDoc(); ReadErrorReport(); ReadFeatures(); ReadImports(); ReadOptions(); ReadPlatform(); ReadReferences(); ReadSigning(); ReadVbRuntime(); AddIfNotNullOrWhiteSpace("baseaddress", Project.ReadPropertyString(PropertyNames.BaseAddress)); AddIfNotNullOrWhiteSpace("define", Project.ReadPropertyString(PropertyNames.FinalDefineConstants)); AddIfNotNullOrWhiteSpace("filealign", Project.ReadPropertyString(PropertyNames.FileAlignment)); AddIfTrue("highentropyva", Project.ReadPropertyBool(PropertyNames.HighEntropyVA)); AddIfNotNullOrWhiteSpace("langversion", Project.ReadPropertyString(PropertyNames.LangVersion)); AddIfNotNullOrWhiteSpace("main", Project.ReadPropertyString(PropertyNames.StartupObject)); AddIfNotNullOrWhiteSpace("moduleassemblyname", Project.ReadPropertyString(PropertyNames.ModuleAssemblyName)); AddIfTrue("netcf", Project.ReadPropertyBool(PropertyNames.TargetCompactFramework)); AddIfTrue("nostdlib", Project.ReadPropertyBool(PropertyNames.NoCompilerStandardLib)); AddIfNotNullOrWhiteSpace("nowarn", Project.ReadPropertyString(PropertyNames.NoWarn)); AddIfTrue("nowarn", Project.ReadPropertyBool(PropertyNames._NoWarnings)); AddIfTrue("optimize", Project.ReadPropertyBool(PropertyNames.Optimize)); AddIfNotNullOrWhiteSpace("out", Project.ReadItemsAsString(PropertyNames.IntermediateAssembly)); AddIfTrue("removeintchecks", Project.ReadPropertyBool(PropertyNames.RemoveIntegerChecks)); AddIfNotNullOrWhiteSpace("rootnamespace", Project.ReadPropertyString(PropertyNames.RootNamespace)); AddIfNotNullOrWhiteSpace("ruleset", Project.ReadPropertyString(PropertyNames.ResolvedCodeAnalysisRuleSet)); AddIfNotNullOrWhiteSpace("sdkpath", Project.ReadPropertyString(PropertyNames.FrameworkPathOverride)); AddIfNotNullOrWhiteSpace("subsystemversion", Project.ReadPropertyString(PropertyNames.SubsystemVersion)); AddIfNotNullOrWhiteSpace("target", Project.ReadPropertyString(PropertyNames.OutputType)); AddIfTrue("warnaserror", Project.ReadPropertyBool(PropertyNames.TreatWarningsAsErrors)); AddIfNotNullOrWhiteSpace("warnaserror+", Project.ReadPropertyString(PropertyNames.WarningsAsErrors)); AddIfNotNullOrWhiteSpace("warnaserror-", Project.ReadPropertyString(PropertyNames.WarningsNotAsErrors)); } private void ReadDoc() { var documentationFile = Project.ReadPropertyString(PropertyNames.DocFileItem); var generateDocumentation = Project.ReadPropertyBool(PropertyNames.GenerateDocumentation); var hasDocumentationFile = !RoslynString.IsNullOrWhiteSpace(documentationFile); if (hasDocumentationFile || generateDocumentation) { if (!RoslynString.IsNullOrWhiteSpace(documentationFile)) { Add("doc", documentationFile); } else { Add("doc"); } } } private void ReadOptions() { var optionCompare = Project.ReadPropertyString(PropertyNames.OptionCompare); if (string.Equals("binary", optionCompare, StringComparison.OrdinalIgnoreCase)) { Add("optioncompare", "binary"); } else if (string.Equals("text", optionCompare, StringComparison.OrdinalIgnoreCase)) { Add("optioncompare", "text"); } // default is on/true AddIfFalse("optionexplicit-", Project.ReadPropertyBool(PropertyNames.OptionExplicit)); AddIfTrue("optioninfer", Project.ReadPropertyBool(PropertyNames.OptionInfer)); AddWithPlusOrMinus("optionstrict", Project.ReadPropertyBool(PropertyNames.OptionStrict)); AddIfNotNullOrWhiteSpace("optionstrict", Project.ReadPropertyString(PropertyNames.OptionStrictType)); } private void ReadVbRuntime() { var vbRuntime = Project.ReadPropertyString(PropertyNames.VbRuntime); if (!RoslynString.IsNullOrWhiteSpace(vbRuntime)) { if (string.Equals("default", vbRuntime, StringComparison.OrdinalIgnoreCase)) { Add("vbruntime+"); } else if (string.Equals("embed", vbRuntime, StringComparison.OrdinalIgnoreCase)) { Add("vbruntime*"); } else if (string.Equals("none", vbRuntime, StringComparison.OrdinalIgnoreCase)) { Add("vbruntime-"); } else { Add("vbruntime", vbRuntime); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using Microsoft.CodeAnalysis.MSBuild; using Roslyn.Utilities; using MSB = Microsoft.Build; namespace Microsoft.CodeAnalysis.VisualBasic { internal class VisualBasicCommandLineArgumentReader : CommandLineArgumentReader { public VisualBasicCommandLineArgumentReader(MSB.Execution.ProjectInstance project) : base(project) { } public static ImmutableArray<string> Read(MSB.Execution.ProjectInstance project) { return new VisualBasicCommandLineArgumentReader(project).Read(); } protected override void ReadCore() { ReadAdditionalFiles(); ReadAnalyzers(); ReadCodePage(); ReadDebugInfo(); ReadDelaySign(); ReadDoc(); ReadErrorReport(); ReadFeatures(); ReadImports(); ReadOptions(); ReadPlatform(); ReadReferences(); ReadSigning(); ReadVbRuntime(); AddIfNotNullOrWhiteSpace("baseaddress", Project.ReadPropertyString(PropertyNames.BaseAddress)); AddIfNotNullOrWhiteSpace("define", Project.ReadPropertyString(PropertyNames.FinalDefineConstants)); AddIfNotNullOrWhiteSpace("filealign", Project.ReadPropertyString(PropertyNames.FileAlignment)); AddIfTrue("highentropyva", Project.ReadPropertyBool(PropertyNames.HighEntropyVA)); AddIfNotNullOrWhiteSpace("langversion", Project.ReadPropertyString(PropertyNames.LangVersion)); AddIfNotNullOrWhiteSpace("main", Project.ReadPropertyString(PropertyNames.StartupObject)); AddIfNotNullOrWhiteSpace("moduleassemblyname", Project.ReadPropertyString(PropertyNames.ModuleAssemblyName)); AddIfTrue("netcf", Project.ReadPropertyBool(PropertyNames.TargetCompactFramework)); AddIfTrue("nostdlib", Project.ReadPropertyBool(PropertyNames.NoCompilerStandardLib)); AddIfNotNullOrWhiteSpace("nowarn", Project.ReadPropertyString(PropertyNames.NoWarn)); AddIfTrue("nowarn", Project.ReadPropertyBool(PropertyNames._NoWarnings)); AddIfTrue("optimize", Project.ReadPropertyBool(PropertyNames.Optimize)); AddIfNotNullOrWhiteSpace("out", Project.ReadItemsAsString(PropertyNames.IntermediateAssembly)); AddIfTrue("removeintchecks", Project.ReadPropertyBool(PropertyNames.RemoveIntegerChecks)); AddIfNotNullOrWhiteSpace("rootnamespace", Project.ReadPropertyString(PropertyNames.RootNamespace)); AddIfNotNullOrWhiteSpace("ruleset", Project.ReadPropertyString(PropertyNames.ResolvedCodeAnalysisRuleSet)); AddIfNotNullOrWhiteSpace("sdkpath", Project.ReadPropertyString(PropertyNames.FrameworkPathOverride)); AddIfNotNullOrWhiteSpace("subsystemversion", Project.ReadPropertyString(PropertyNames.SubsystemVersion)); AddIfNotNullOrWhiteSpace("target", Project.ReadPropertyString(PropertyNames.OutputType)); AddIfTrue("warnaserror", Project.ReadPropertyBool(PropertyNames.TreatWarningsAsErrors)); AddIfNotNullOrWhiteSpace("warnaserror+", Project.ReadPropertyString(PropertyNames.WarningsAsErrors)); AddIfNotNullOrWhiteSpace("warnaserror-", Project.ReadPropertyString(PropertyNames.WarningsNotAsErrors)); } private void ReadDoc() { var documentationFile = Project.ReadPropertyString(PropertyNames.DocFileItem); var generateDocumentation = Project.ReadPropertyBool(PropertyNames.GenerateDocumentation); var hasDocumentationFile = !RoslynString.IsNullOrWhiteSpace(documentationFile); if (hasDocumentationFile || generateDocumentation) { if (!RoslynString.IsNullOrWhiteSpace(documentationFile)) { Add("doc", documentationFile); } else { Add("doc"); } } } private void ReadOptions() { var optionCompare = Project.ReadPropertyString(PropertyNames.OptionCompare); if (string.Equals("binary", optionCompare, StringComparison.OrdinalIgnoreCase)) { Add("optioncompare", "binary"); } else if (string.Equals("text", optionCompare, StringComparison.OrdinalIgnoreCase)) { Add("optioncompare", "text"); } // default is on/true AddIfFalse("optionexplicit-", Project.ReadPropertyBool(PropertyNames.OptionExplicit)); AddIfTrue("optioninfer", Project.ReadPropertyBool(PropertyNames.OptionInfer)); AddWithPlusOrMinus("optionstrict", Project.ReadPropertyBool(PropertyNames.OptionStrict)); AddIfNotNullOrWhiteSpace("optionstrict", Project.ReadPropertyString(PropertyNames.OptionStrictType)); } private void ReadVbRuntime() { var vbRuntime = Project.ReadPropertyString(PropertyNames.VbRuntime); if (!RoslynString.IsNullOrWhiteSpace(vbRuntime)) { if (string.Equals("default", vbRuntime, StringComparison.OrdinalIgnoreCase)) { Add("vbruntime+"); } else if (string.Equals("embed", vbRuntime, StringComparison.OrdinalIgnoreCase)) { Add("vbruntime*"); } else if (string.Equals("none", vbRuntime, StringComparison.OrdinalIgnoreCase)) { Add("vbruntime-"); } else { Add("vbruntime", vbRuntime); } } } } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/Compilers/Core/Portable/Emit/AsyncMoveNextBodyDebugInfo.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; namespace Microsoft.CodeAnalysis.Emit { /// <summary> /// Represents additional info needed by async method implementation methods /// (MoveNext methods) to properly emit necessary PDB data for async debugging. /// </summary> internal sealed class AsyncMoveNextBodyDebugInfo : StateMachineMoveNextBodyDebugInfo { /// <summary> /// IL offset of catch handler or -1 /// </summary> public readonly int CatchHandlerOffset; /// <summary> /// Set of IL offsets where await operators yield control /// </summary> public readonly ImmutableArray<int> YieldOffsets; /// <summary> /// Set of IL offsets where await operators are to be resumed /// </summary> public readonly ImmutableArray<int> ResumeOffsets; public AsyncMoveNextBodyDebugInfo( Cci.IMethodDefinition kickoffMethod, int catchHandlerOffset, ImmutableArray<int> yieldOffsets, ImmutableArray<int> resumeOffsets) : base(kickoffMethod) { Debug.Assert(!yieldOffsets.IsDefault); Debug.Assert(!resumeOffsets.IsDefault); Debug.Assert(yieldOffsets.Length == resumeOffsets.Length); CatchHandlerOffset = catchHandlerOffset; YieldOffsets = yieldOffsets; ResumeOffsets = resumeOffsets; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; namespace Microsoft.CodeAnalysis.Emit { /// <summary> /// Represents additional info needed by async method implementation methods /// (MoveNext methods) to properly emit necessary PDB data for async debugging. /// </summary> internal sealed class AsyncMoveNextBodyDebugInfo : StateMachineMoveNextBodyDebugInfo { /// <summary> /// IL offset of catch handler or -1 /// </summary> public readonly int CatchHandlerOffset; /// <summary> /// Set of IL offsets where await operators yield control /// </summary> public readonly ImmutableArray<int> YieldOffsets; /// <summary> /// Set of IL offsets where await operators are to be resumed /// </summary> public readonly ImmutableArray<int> ResumeOffsets; public AsyncMoveNextBodyDebugInfo( Cci.IMethodDefinition kickoffMethod, int catchHandlerOffset, ImmutableArray<int> yieldOffsets, ImmutableArray<int> resumeOffsets) : base(kickoffMethod) { Debug.Assert(!yieldOffsets.IsDefault); Debug.Assert(!resumeOffsets.IsDefault); Debug.Assert(yieldOffsets.Length == resumeOffsets.Length); CatchHandlerOffset = catchHandlerOffset; YieldOffsets = yieldOffsets; ResumeOffsets = resumeOffsets; } } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/Tools/IdeCoreBenchmarks/SyntacticChangeRangeBenchmark.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.IO; using System.Threading; using BenchmarkDotNet.Attributes; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Text; namespace IdeCoreBenchmarks { [MemoryDiagnoser] public class SyntacticChangeRangeBenchmark { private int _index; private SourceText _text; private SyntaxTree _tree; private SyntaxNode _root; private SyntaxNode _rootWithSimpleEdit; private SyntaxNode _rootWithComplexEdit; [GlobalSetup] public void GlobalSetup() { var roslynRoot = Environment.GetEnvironmentVariable(Program.RoslynRootPathEnvVariableName); var csFilePath = Path.Combine(roslynRoot, @"src\Compilers\CSharp\Portable\Generated\BoundNodes.xml.Generated.cs"); if (!File.Exists(csFilePath)) throw new FileNotFoundException(csFilePath); var text = File.ReadAllText(csFilePath); _index = text.IndexOf("switch (node.Kind)"); if (_index < 0) throw new ArgumentException("Code location not found"); _text = SourceText.From(text); _tree = SyntaxFactory.ParseSyntaxTree(_text); _root = _tree.GetCompilationUnitRoot(); _rootWithSimpleEdit = WithSimpleEditAtMiddle(); _rootWithComplexEdit = WithDestabalizingEditAtMiddle(); } private SyntaxNode WithSimpleEditAtMiddle() { // this will change the switch statement to `mode.kind` instead of `node.kind`. This should be reuse most // of the tree and should result in a very small diff. var newText = _text.WithChanges(new TextChange(new TextSpan(_index + 8, 1), "m")); var newTree = _tree.WithChangedText(newText); var newRoot = newTree.GetRoot(); return newRoot; } private SyntaxNode WithDestabalizingEditAtMiddle() { // this will change the switch statement to a switch expression. This may have large cascading changes. var newText = _text.WithChanges(new TextChange(new TextSpan(_index, 0), "var v = x ")); var newTree = _tree.WithChangedText(newText); var newRoot = newTree.GetRoot(); return newRoot; } [Benchmark] public void SimpleEditAtMiddle() { var newRoot = WithSimpleEditAtMiddle(); SyntacticChangeRangeComputer.ComputeSyntacticChangeRange(_root, newRoot, TimeSpan.MaxValue, CancellationToken.None); } [Benchmark] public void DestabalizingEditAtMiddle() { var newRoot = WithDestabalizingEditAtMiddle(); SyntacticChangeRangeComputer.ComputeSyntacticChangeRange(_root, newRoot, TimeSpan.MaxValue, CancellationToken.None); } [Benchmark] public void SimpleEditAtMiddle_NoParse() { SyntacticChangeRangeComputer.ComputeSyntacticChangeRange(_root, _rootWithSimpleEdit, TimeSpan.MaxValue, CancellationToken.None); } [Benchmark] public void DestabalizingEditAtMiddle_NoParse() { SyntacticChangeRangeComputer.ComputeSyntacticChangeRange(_root, _rootWithComplexEdit, TimeSpan.MaxValue, CancellationToken.None); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.IO; using System.Threading; using BenchmarkDotNet.Attributes; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Text; namespace IdeCoreBenchmarks { [MemoryDiagnoser] public class SyntacticChangeRangeBenchmark { private int _index; private SourceText _text; private SyntaxTree _tree; private SyntaxNode _root; private SyntaxNode _rootWithSimpleEdit; private SyntaxNode _rootWithComplexEdit; [GlobalSetup] public void GlobalSetup() { var roslynRoot = Environment.GetEnvironmentVariable(Program.RoslynRootPathEnvVariableName); var csFilePath = Path.Combine(roslynRoot, @"src\Compilers\CSharp\Portable\Generated\BoundNodes.xml.Generated.cs"); if (!File.Exists(csFilePath)) throw new FileNotFoundException(csFilePath); var text = File.ReadAllText(csFilePath); _index = text.IndexOf("switch (node.Kind)"); if (_index < 0) throw new ArgumentException("Code location not found"); _text = SourceText.From(text); _tree = SyntaxFactory.ParseSyntaxTree(_text); _root = _tree.GetCompilationUnitRoot(); _rootWithSimpleEdit = WithSimpleEditAtMiddle(); _rootWithComplexEdit = WithDestabalizingEditAtMiddle(); } private SyntaxNode WithSimpleEditAtMiddle() { // this will change the switch statement to `mode.kind` instead of `node.kind`. This should be reuse most // of the tree and should result in a very small diff. var newText = _text.WithChanges(new TextChange(new TextSpan(_index + 8, 1), "m")); var newTree = _tree.WithChangedText(newText); var newRoot = newTree.GetRoot(); return newRoot; } private SyntaxNode WithDestabalizingEditAtMiddle() { // this will change the switch statement to a switch expression. This may have large cascading changes. var newText = _text.WithChanges(new TextChange(new TextSpan(_index, 0), "var v = x ")); var newTree = _tree.WithChangedText(newText); var newRoot = newTree.GetRoot(); return newRoot; } [Benchmark] public void SimpleEditAtMiddle() { var newRoot = WithSimpleEditAtMiddle(); SyntacticChangeRangeComputer.ComputeSyntacticChangeRange(_root, newRoot, TimeSpan.MaxValue, CancellationToken.None); } [Benchmark] public void DestabalizingEditAtMiddle() { var newRoot = WithDestabalizingEditAtMiddle(); SyntacticChangeRangeComputer.ComputeSyntacticChangeRange(_root, newRoot, TimeSpan.MaxValue, CancellationToken.None); } [Benchmark] public void SimpleEditAtMiddle_NoParse() { SyntacticChangeRangeComputer.ComputeSyntacticChangeRange(_root, _rootWithSimpleEdit, TimeSpan.MaxValue, CancellationToken.None); } [Benchmark] public void DestabalizingEditAtMiddle_NoParse() { SyntacticChangeRangeComputer.ComputeSyntacticChangeRange(_root, _rootWithComplexEdit, TimeSpan.MaxValue, CancellationToken.None); } } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/Workspaces/Core/Portable/Storage/SQLite/v2/SQLitePersistentStorage_FlushWrites.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using System.Threading.Tasks; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.SQLite.v2 { internal partial class SQLitePersistentStorage { /// <summary> /// A queue to batch up flush requests and ensure that we don't issue then more often than every <see /// cref="FlushAllDelayMS"/>. /// </summary> private readonly AsyncBatchingWorkQueue _flushQueue; private void EnqueueFlushTask() { _flushQueue.AddWork(); } private async ValueTask FlushInMemoryDataToDiskIfNotShutdownAsync(CancellationToken cancellationToken) { // When we are asked to flush, go actually acquire the write-scheduler and perform the actual writes from // it. Note: this is only called max every FlushAllDelayMS. So we don't bother trying to avoid the delegate // allocation here. await PerformWriteAsync(_flushInMemoryDataToDisk, cancellationToken).ConfigureAwait(false); } private Task FlushWritesOnCloseAsync() { // Issue a write task to write this all out to disk. // // Note: this only happens on close, so we don't try to avoid allocations here. return PerformWriteAsync( () => { // Perform the actual write while having exclusive access to the scheduler. FlushInMemoryDataToDisk(); // Now that we've done this, definitely cancel any further work. From this point on, it is now // invalid for any codepaths to try to acquire a db connection for any purpose (beyond us // disposing things below). // // This will also ensure that if we have a bg flush task still pending, when it wakes up it will // see that we're shutdown and not proceed (and importantly won't acquire a connection). Because // both the bg task and us run serialized, there is no way for it to miss this token // cancellation. If it runs after us, then it sees this. If it runs before us, then we just // block until it finishes. // // We don't have to worry about reads/writes getting connections either. // The only way we can get disposed in the first place is if every user of this storage instance // has released their ref on us. In that case, it would be an error on their part to ever try to // read/write after releasing us. _shutdownTokenSource.Cancel(); }, CancellationToken.None); } private void FlushInMemoryDataToDisk() { // We're writing. This better always be under the exclusive scheduler. Contract.ThrowIfFalse(TaskScheduler.Current == _connectionPoolService.Scheduler.ExclusiveScheduler); // Don't flush from a bg task if we've been asked to shutdown. The shutdown logic in the storage service // will take care of the final writes to the main db. if (_shutdownTokenSource.IsCancellationRequested) return; using var _ = _connectionPool.Target.GetPooledConnection(out var connection); connection.RunInTransaction(static state => { state.self._solutionAccessor.FlushInMemoryDataToDisk_MustRunInTransaction(state.connection); state.self._projectAccessor.FlushInMemoryDataToDisk_MustRunInTransaction(state.connection); state.self._documentAccessor.FlushInMemoryDataToDisk_MustRunInTransaction(state.connection); }, (self: this, connection)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using System.Threading.Tasks; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.SQLite.v2 { internal partial class SQLitePersistentStorage { /// <summary> /// A queue to batch up flush requests and ensure that we don't issue then more often than every <see /// cref="FlushAllDelayMS"/>. /// </summary> private readonly AsyncBatchingWorkQueue _flushQueue; private void EnqueueFlushTask() { _flushQueue.AddWork(); } private async ValueTask FlushInMemoryDataToDiskIfNotShutdownAsync(CancellationToken cancellationToken) { // When we are asked to flush, go actually acquire the write-scheduler and perform the actual writes from // it. Note: this is only called max every FlushAllDelayMS. So we don't bother trying to avoid the delegate // allocation here. await PerformWriteAsync(_flushInMemoryDataToDisk, cancellationToken).ConfigureAwait(false); } private Task FlushWritesOnCloseAsync() { // Issue a write task to write this all out to disk. // // Note: this only happens on close, so we don't try to avoid allocations here. return PerformWriteAsync( () => { // Perform the actual write while having exclusive access to the scheduler. FlushInMemoryDataToDisk(); // Now that we've done this, definitely cancel any further work. From this point on, it is now // invalid for any codepaths to try to acquire a db connection for any purpose (beyond us // disposing things below). // // This will also ensure that if we have a bg flush task still pending, when it wakes up it will // see that we're shutdown and not proceed (and importantly won't acquire a connection). Because // both the bg task and us run serialized, there is no way for it to miss this token // cancellation. If it runs after us, then it sees this. If it runs before us, then we just // block until it finishes. // // We don't have to worry about reads/writes getting connections either. // The only way we can get disposed in the first place is if every user of this storage instance // has released their ref on us. In that case, it would be an error on their part to ever try to // read/write after releasing us. _shutdownTokenSource.Cancel(); }, CancellationToken.None); } private void FlushInMemoryDataToDisk() { // We're writing. This better always be under the exclusive scheduler. Contract.ThrowIfFalse(TaskScheduler.Current == _connectionPoolService.Scheduler.ExclusiveScheduler); // Don't flush from a bg task if we've been asked to shutdown. The shutdown logic in the storage service // will take care of the final writes to the main db. if (_shutdownTokenSource.IsCancellationRequested) return; using var _ = _connectionPool.Target.GetPooledConnection(out var connection); connection.RunInTransaction(static state => { state.self._solutionAccessor.FlushInMemoryDataToDisk_MustRunInTransaction(state.connection); state.self._projectAccessor.FlushInMemoryDataToDisk_MustRunInTransaction(state.connection); state.self._documentAccessor.FlushInMemoryDataToDisk_MustRunInTransaction(state.connection); }, (self: this, connection)); } } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/Compilers/CSharp/Test/Syntax/Syntax/SyntaxNormalizerTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Text; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; using System; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class SyntaxNormalizerTests { [Fact, WorkItem(52543, "https://github.com/dotnet/roslyn/issues/52543")] public void TestNormalizePatternInIf() { TestNormalizeStatement( @"{object x = 1; if (x is {}) { } if (x is {} t) { } if (x is int {} t2) { } if (x is System.ValueTuple<int, int>(_, _) { Item1: > 10 } t3) { } if (x is System.ValueTuple<int, int>(_, _) { Item1: > 10, Item2: < 20 }) { } }", @"{ object x = 1; if (x is { }) { } if (x is { } t) { } if (x is int { } t2) { } if (x is System.ValueTuple<int, int> (_, _) { Item1: > 10 } t3) { } if (x is System.ValueTuple<int, int> (_, _) { Item1: > 10, Item2: < 20 }) { } }".NormalizeLineEndings() ); } [Fact, WorkItem(52543, "https://github.com/dotnet/roslyn/issues/52543")] public void TestNormalizeSwitchExpression() { TestNormalizeStatement( @"var x = (int)1 switch { 1 => ""one"", 2 => ""two"", 3 => ""three"", {} => "">= 4"" };", @"var x = (int)1 switch { 1 => ""one"", 2 => ""two"", 3 => ""three"", { } => "">= 4"" };".NormalizeLineEndings() ); } [Fact, WorkItem(52543, "https://github.com/dotnet/roslyn/issues/52543")] public void TestNormalizeSwitchRecPattern() { TestNormalizeStatement( @"var x = (object)1 switch { int { } => ""two"", { } t when t.GetHashCode() == 42 => ""42"", System.ValueTuple<int, int> (1, _) { Item2: > 2 and < 20 } => ""tuple.Item2 < 20"", System.ValueTuple<int, int> (1, _) { Item2: >= 100 } greater => greater.ToString(), System.ValueType {} => ""not null value"", object {} i when i is not 42 => ""not 42"", { } => ""not null"", null => ""null"", };", @"var x = (object)1 switch { int { } => ""two"", { } t when t.GetHashCode() == 42 => ""42"", System.ValueTuple<int, int> (1, _) { Item2: > 2 and < 20 } => ""tuple.Item2 < 20"", System.ValueTuple<int, int> (1, _) { Item2: >= 100 } greater => greater.ToString(), System.ValueType { } => ""not null value"", object { } i when i is not 42 => ""not 42"", { } => ""not null"", null => ""null"", };".NormalizeLineEndings() ); } [Fact, WorkItem(52543, "https://github.com/dotnet/roslyn/issues/52543")] public void TestNormalizeSwitchExpressionComplex() { var a = @"var x = vehicle switch { Car { Passengers: 0 } => 2.00m + 0.50m, Car { Passengers: 1 } => 2.0m, Car { Passengers: 2 } => 2.0m - 0.50m, Car c => 2.00m - 1.0m, Taxi { Fares: 0 } => 3.50m + 1.00m, Taxi { Fares: 1 } => 3.50m, Taxi { Fares: 2 } => 3.50m - 0.50m, Taxi t => 3.50m - 1.00m, Bus b when ((double)b.Riders / (double)b.Capacity) < 0.50 => 5.00m + 2.00m, Bus b when ((double)b.Riders / (double)b.Capacity) > 0.90 => 5.00m - 1.00m, Bus b => 5.00m, DeliveryTruck t when (t.GrossWeightClass > 5000) => 10.00m + 5.00m, DeliveryTruck t when (t.GrossWeightClass < 3000) => 10.00m - 2.00m, DeliveryTruck t => 10.00m, { } => -1, //throw new ArgumentException(message: ""Not a known vehicle type"", paramName: nameof(vehicle)), null => 0//throw new ArgumentNullException(nameof(vehicle)) };"; var b = @"var x = vehicle switch { Car { Passengers: 0 } => 2.00m + 0.50m, Car { Passengers: 1 } => 2.0m, Car { Passengers: 2 } => 2.0m - 0.50m, Car c => 2.00m - 1.0m, Taxi { Fares: 0 } => 3.50m + 1.00m, Taxi { Fares: 1 } => 3.50m, Taxi { Fares: 2 } => 3.50m - 0.50m, Taxi t => 3.50m - 1.00m, Bus b when ((double)b.Riders / (double)b.Capacity) < 0.50 => 5.00m + 2.00m, Bus b when ((double)b.Riders / (double)b.Capacity) > 0.90 => 5.00m - 1.00m, Bus b => 5.00m, DeliveryTruck t when (t.GrossWeightClass > 5000) => 10.00m + 5.00m, DeliveryTruck t when (t.GrossWeightClass < 3000) => 10.00m - 2.00m, DeliveryTruck t => 10.00m, { } => -1, //throw new ArgumentException(message: ""Not a known vehicle type"", paramName: nameof(vehicle)), null => 0 //throw new ArgumentNullException(nameof(vehicle)) };".NormalizeLineEndings(); TestNormalizeStatement(a, b); } [Fact, WorkItem(50742, "https://github.com/dotnet/roslyn/issues/50742")] public void TestLineBreakInterpolations() { TestNormalizeExpression( @"$""Printed: { new Printer() { TextToPrint = ""Hello world!"" }.PrintedText }""", @"$""Printed: {new Printer(){TextToPrint = ""Hello world!""}.PrintedText}""" ); } [Fact, WorkItem(50742, "https://github.com/dotnet/roslyn/issues/50742")] public void TestVerbatimStringInterpolationWithLineBreaks() { TestNormalizeStatement(@"Console.WriteLine($@""Test with line breaks { new[]{ 1, 2, 3 }[2] } "");", @"Console.WriteLine($@""Test with line breaks {new[]{1, 2, 3}[2]} "");" ); } [Fact] public void TestNormalizeExpression1() { TestNormalizeExpression("!a", "!a"); TestNormalizeExpression("-a", "-a"); TestNormalizeExpression("+a", "+a"); TestNormalizeExpression("~a", "~a"); TestNormalizeExpression("a", "a"); TestNormalizeExpression("a+b", "a + b"); TestNormalizeExpression("a-b", "a - b"); TestNormalizeExpression("a*b", "a * b"); TestNormalizeExpression("a/b", "a / b"); TestNormalizeExpression("a%b", "a % b"); TestNormalizeExpression("a^b", "a ^ b"); TestNormalizeExpression("a|b", "a | b"); TestNormalizeExpression("a&b", "a & b"); TestNormalizeExpression("a||b", "a || b"); TestNormalizeExpression("a&&b", "a && b"); TestNormalizeExpression("a<b", "a < b"); TestNormalizeExpression("a<=b", "a <= b"); TestNormalizeExpression("a>b", "a > b"); TestNormalizeExpression("a>=b", "a >= b"); TestNormalizeExpression("a==b", "a == b"); TestNormalizeExpression("a!=b", "a != b"); TestNormalizeExpression("a<<b", "a << b"); TestNormalizeExpression("a>>b", "a >> b"); TestNormalizeExpression("a??b", "a ?? b"); TestNormalizeExpression("a<b>.c", "a<b>.c"); TestNormalizeExpression("(a+b)", "(a + b)"); TestNormalizeExpression("((a)+(b))", "((a) + (b))"); TestNormalizeExpression("(a)b", "(a)b"); TestNormalizeExpression("(a)(b)", "(a)(b)"); TestNormalizeExpression("m()", "m()"); TestNormalizeExpression("m(a)", "m(a)"); TestNormalizeExpression("m(a,b)", "m(a, b)"); TestNormalizeExpression("m(a,b,c)", "m(a, b, c)"); TestNormalizeExpression("m(a,b(c,d))", "m(a, b(c, d))"); TestNormalizeExpression("a?b:c", "a ? b : c"); TestNormalizeExpression("from a in b where c select d", "from a in b\r\nwhere c\r\nselect d"); TestNormalizeExpression("a().b().c()", "a().b().c()"); TestNormalizeExpression("a->b->c", "a->b->c"); TestNormalizeExpression("global :: a", "global::a"); TestNormalizeExpression("(IList<int>)args", "(IList<int>)args"); TestNormalizeExpression("(IList<IList<int>>)args", "(IList<IList<int>>)args"); TestNormalizeExpression("(IList<string?>)args", "(IList<string?>)args"); } private void TestNormalizeExpression(string text, string expected) { var node = SyntaxFactory.ParseExpression(text); var actual = node.NormalizeWhitespace(" ").ToFullString(); Assert.Equal(expected, actual); } [Fact] public void TestNormalizeStatement1() { // expressions TestNormalizeStatement("a;", "a;"); // blocks TestNormalizeStatement("{a;}", "{\r\n a;\r\n}"); TestNormalizeStatement("{a;b;}", "{\r\n a;\r\n b;\r\n}"); TestNormalizeStatement("\t{a;}", "{\r\n a;\r\n}"); TestNormalizeStatement("\t{a;b;}", "{\r\n a;\r\n b;\r\n}"); // if TestNormalizeStatement("if(a)b;", "if (a)\r\n b;"); TestNormalizeStatement("if(a){b;}", "if (a)\r\n{\r\n b;\r\n}"); TestNormalizeStatement("if(a){b;c;}", "if (a)\r\n{\r\n b;\r\n c;\r\n}"); TestNormalizeStatement("if(a)b;else c;", "if (a)\r\n b;\r\nelse\r\n c;"); TestNormalizeStatement("if(a)b;else if(c)d;", "if (a)\r\n b;\r\nelse if (c)\r\n d;"); // while TestNormalizeStatement("while(a)b;", "while (a)\r\n b;"); TestNormalizeStatement("while(a){b;}", "while (a)\r\n{\r\n b;\r\n}"); // do TestNormalizeStatement("do{a;}while(b);", "do\r\n{\r\n a;\r\n}\r\nwhile (b);"); // for TestNormalizeStatement("for(a;b;c)d;", "for (a; b; c)\r\n d;"); TestNormalizeStatement("for(;;)a;", "for (;;)\r\n a;"); // foreach TestNormalizeStatement("foreach(a in b)c;", "foreach (a in b)\r\n c;"); // try TestNormalizeStatement("try{a;}catch(b){c;}", "try\r\n{\r\n a;\r\n}\r\ncatch (b)\r\n{\r\n c;\r\n}"); TestNormalizeStatement("try{a;}finally{b;}", "try\r\n{\r\n a;\r\n}\r\nfinally\r\n{\r\n b;\r\n}"); // other TestNormalizeStatement("lock(a)b;", "lock (a)\r\n b;"); TestNormalizeStatement("fixed(a)b;", "fixed (a)\r\n b;"); TestNormalizeStatement("using(a)b;", "using (a)\r\n b;"); TestNormalizeStatement("checked{a;}", "checked\r\n{\r\n a;\r\n}"); TestNormalizeStatement("unchecked{a;}", "unchecked\r\n{\r\n a;\r\n}"); TestNormalizeStatement("unsafe{a;}", "unsafe\r\n{\r\n a;\r\n}"); // declaration statements TestNormalizeStatement("a b;", "a b;"); TestNormalizeStatement("a?b;", "a? b;"); TestNormalizeStatement("a b,c;", "a b, c;"); TestNormalizeStatement("a b=c;", "a b = c;"); TestNormalizeStatement("a b=c,d=e;", "a b = c, d = e;"); // empty statements TestNormalizeStatement(";", ";"); TestNormalizeStatement("{;;}", "{\r\n ;\r\n ;\r\n}"); // labelled statements TestNormalizeStatement("goo:;", "goo:\r\n ;"); TestNormalizeStatement("goo:a;", "goo:\r\n a;"); // return/goto TestNormalizeStatement("return;", "return;"); TestNormalizeStatement("return(a);", "return (a);"); TestNormalizeStatement("continue;", "continue;"); TestNormalizeStatement("break;", "break;"); TestNormalizeStatement("yield return;", "yield return;"); TestNormalizeStatement("yield return(a);", "yield return (a);"); TestNormalizeStatement("yield break;", "yield break;"); TestNormalizeStatement("goto a;", "goto a;"); TestNormalizeStatement("throw;", "throw;"); TestNormalizeStatement("throw a;", "throw a;"); TestNormalizeStatement("return this.Bar()", "return this.Bar()"); // switch TestNormalizeStatement("switch(a){case b:c;}", "switch (a)\r\n{\r\n case b:\r\n c;\r\n}"); TestNormalizeStatement("switch(a){case b:c;case d:e;}", "switch (a)\r\n{\r\n case b:\r\n c;\r\n case d:\r\n e;\r\n}"); TestNormalizeStatement("switch(a){case b:c;default:d;}", "switch (a)\r\n{\r\n case b:\r\n c;\r\n default:\r\n d;\r\n}"); TestNormalizeStatement("switch(a){case b:{}default:{}}", "switch (a)\r\n{\r\n case b:\r\n {\r\n }\r\n\r\n default:\r\n {\r\n }\r\n}"); TestNormalizeStatement("switch(a){case b:c();d();default:e();f();}", "switch (a)\r\n{\r\n case b:\r\n c();\r\n d();\r\n default:\r\n e();\r\n f();\r\n}"); TestNormalizeStatement("switch(a){case b:{c();}}", "switch (a)\r\n{\r\n case b:\r\n {\r\n c();\r\n }\r\n}"); // curlies TestNormalizeStatement("{if(goo){}if(bar){}}", "{\r\n if (goo)\r\n {\r\n }\r\n\r\n if (bar)\r\n {\r\n }\r\n}"); // Queries TestNormalizeStatement("int i=from v in vals select v;", "int i =\r\n from v in vals\r\n select v;"); TestNormalizeStatement("Goo(from v in vals select v);", "Goo(\r\n from v in vals\r\n select v);"); TestNormalizeStatement("int i=from v in vals select from x in xxx where x > 10 select x;", "int i =\r\n from v in vals\r\n select\r\n from x in xxx\r\n where x > 10\r\n select x;"); TestNormalizeStatement("int i=from v in vals group v by x into g where g > 10 select g;", "int i =\r\n from v in vals\r\n group v by x into g\r\n where g > 10\r\n select g;"); // Generics TestNormalizeStatement("Func<string, int> f = blah;", "Func<string, int> f = blah;"); } [Theory] [InlineData("int*p;", "int* p;")] [InlineData("int *p;", "int* p;")] [InlineData("int*p1,p2;", "int* p1, p2;")] [InlineData("int *p1, p2;", "int* p1, p2;")] [InlineData("int**p;", "int** p;")] [InlineData("int **p;", "int** p;")] [InlineData("int**p1,p2;", "int** p1, p2;")] [InlineData("int **p1, p2;", "int** p1, p2;")] [WorkItem(49733, "https://github.com/dotnet/roslyn/issues/49733")] public void TestNormalizeAsteriskInPointerDeclaration(string text, string expected) { TestNormalizeStatement(text, expected); } [Fact] [WorkItem(49733, "https://github.com/dotnet/roslyn/issues/49733")] public void TestNormalizeAsteriskInPointerReturnTypeOfIndexer() { var text = @"public unsafe class C { int*this[int x,int y]{get=>(int*)0;} }"; var expected = @"public unsafe class C { int* this[int x, int y] { get => (int*)0; } }"; TestNormalizeDeclaration(text, expected); } [Fact] public void TestNormalizeAsteriskInVoidPointerCast() { var text = @"public unsafe class C { void*this[int x,int y]{get => ( void * ) 0;} }"; var expected = @"public unsafe class C { void* this[int x, int y] { get => (void*)0; } }"; TestNormalizeDeclaration(text, expected); } private void TestNormalizeStatement(string text, string expected) { var node = SyntaxFactory.ParseStatement(text); var actual = node.NormalizeWhitespace(" ").ToFullString(); Assert.Equal(expected, actual); } [Fact] public void TestNormalizeDeclaration1() { // usings TestNormalizeDeclaration("using a;", "using a;"); TestNormalizeDeclaration("using a=b;", "using a = b;"); TestNormalizeDeclaration("using a.b;", "using a.b;"); TestNormalizeDeclaration("using A; using B; class C {}", "using A;\r\nusing B;\r\n\r\nclass C\r\n{\r\n}"); TestNormalizeDeclaration("global using a;", "global using a;"); TestNormalizeDeclaration("global using a=b;", "global using a = b;"); TestNormalizeDeclaration("global using a.b;", "global using a.b;"); TestNormalizeDeclaration("global using A; global using B; class C {}", "global using A;\r\nglobal using B;\r\n\r\nclass C\r\n{\r\n}"); TestNormalizeDeclaration("global using A; using B; class C {}", "global using A;\r\nusing B;\r\n\r\nclass C\r\n{\r\n}"); TestNormalizeDeclaration("using A; global using B; class C {}", "using A;\r\nglobal using B;\r\n\r\nclass C\r\n{\r\n}"); // namespace TestNormalizeDeclaration("namespace a{}", "namespace a\r\n{\r\n}"); TestNormalizeDeclaration("namespace a{using b;}", "namespace a\r\n{\r\n using b;\r\n}"); TestNormalizeDeclaration("namespace a{global using b;}", "namespace a\r\n{\r\n global using b;\r\n}"); TestNormalizeDeclaration("namespace a{namespace b{}}", "namespace a\r\n{\r\n namespace b\r\n {\r\n }\r\n}"); TestNormalizeDeclaration("namespace a{}namespace b{}", "namespace a\r\n{\r\n}\r\n\r\nnamespace b\r\n{\r\n}"); // type TestNormalizeDeclaration("class a{}", "class a\r\n{\r\n}"); TestNormalizeDeclaration("class a{class b{}}", "class a\r\n{\r\n class b\r\n {\r\n }\r\n}"); TestNormalizeDeclaration("class a<b>where a:c{}", "class a<b>\r\n where a : c\r\n{\r\n}"); TestNormalizeDeclaration("class a<b,c>where a:c{}", "class a<b, c>\r\n where a : c\r\n{\r\n}"); TestNormalizeDeclaration("class a:b{}", "class a : b\r\n{\r\n}"); // methods TestNormalizeDeclaration("class a{void b(){}}", "class a\r\n{\r\n void b()\r\n {\r\n }\r\n}"); TestNormalizeDeclaration("class a{void b(){}void c(){}}", "class a\r\n{\r\n void b()\r\n {\r\n }\r\n\r\n void c()\r\n {\r\n }\r\n}"); TestNormalizeDeclaration("class a{a(){}}", "class a\r\n{\r\n a()\r\n {\r\n }\r\n}"); TestNormalizeDeclaration("class a{~a(){}}", "class a\r\n{\r\n ~a()\r\n {\r\n }\r\n}"); // properties TestNormalizeDeclaration("class a{b c{get;}}", "class a\r\n{\r\n b c { get; }\r\n}"); TestNormalizeDeclaration("class a {\r\nint X{get;set;}= 2;\r\n}\r\n", "class a\r\n{\r\n int X { get; set; } = 2;\r\n}"); TestNormalizeDeclaration("class a {\r\nint Y\r\n{get;\r\nset;\r\n}\r\n=99;\r\n}\r\n", "class a\r\n{\r\n int Y { get; set; } = 99;\r\n}"); TestNormalizeDeclaration("class a {\r\nint Z{get;}\r\n}\r\n", "class a\r\n{\r\n int Z { get; }\r\n}"); TestNormalizeDeclaration("class a {\r\nint T{get;init;}\r\nint R{get=>1;}\r\n}\r\n", "class a\r\n{\r\n int T { get; init; }\r\n\r\n int R { get => 1; }\r\n}"); TestNormalizeDeclaration("class a {\r\nint Q{get{return 0;}init{}}\r\nint R{get=>1;}\r\n}\r\n", "class a\r\n{\r\n int Q\r\n {\r\n get\r\n {\r\n return 0;\r\n }\r\n\r\n init\r\n {\r\n }\r\n }\r\n\r\n int R { get => 1; }\r\n}"); TestNormalizeDeclaration("class a {\r\nint R{get=>1;}\r\n}\r\n", "class a\r\n{\r\n int R { get => 1; }\r\n}"); TestNormalizeDeclaration("class a {\r\nint S=>2;\r\n}\r\n", "class a\r\n{\r\n int S => 2;\r\n}"); TestNormalizeDeclaration("class x\r\n{\r\nint _g;\r\nint G\r\n{\r\nget\r\n{\r\nreturn\r\n_g;\r\n}\r\ninit;\r\n}\r\nint H\r\n{\r\nget;\r\nset\r\n{\r\n_g\r\n=\r\n12;\r\n}\r\n}\r\n}\r\n", "class x\r\n{\r\n int _g;\r\n int G\r\n {\r\n get\r\n {\r\n return _g;\r\n }\r\n\r\n init;\r\n }\r\n\r\n int H\r\n {\r\n get;\r\n set\r\n {\r\n _g = 12;\r\n }\r\n }\r\n}"); TestNormalizeDeclaration("class i1\r\n{\r\nint\r\np\r\n{\r\nget;\r\n}\r\n}", "class i1\r\n{\r\n int p { get; }\r\n}"); TestNormalizeDeclaration("class i2\r\n{\r\nint\r\np\r\n{\r\nget=>2;\r\n}\r\n}", "class i2\r\n{\r\n int p { get => 2; }\r\n}"); TestNormalizeDeclaration("class i2a\r\n{\r\nint _p;\r\nint\r\np\r\n{\r\nget=>\r\n_p;set\r\n=>_p\r\n=value\r\n;\r\n}\r\n}", "class i2a\r\n{\r\n int _p;\r\n int p { get => _p; set => _p = value; }\r\n}"); TestNormalizeDeclaration("class i3\r\n{\r\nint\r\np\r\n{\r\nget{}\r\n}\r\n}", "class i3\r\n{\r\n int p\r\n {\r\n get\r\n {\r\n }\r\n }\r\n}"); TestNormalizeDeclaration("class i4\r\n{\r\nint\r\np\r\n{\r\nset;\r\n}\r\n}", "class i4\r\n{\r\n int p { set; }\r\n}"); TestNormalizeDeclaration("class i5\r\n{\r\nint\r\np\r\n{\r\nset{}\r\n}\r\n}", "class i5\r\n{\r\n int p\r\n {\r\n set\r\n {\r\n }\r\n }\r\n}"); TestNormalizeDeclaration("class i6\r\n{\r\nint\r\np\r\n{\r\ninit;\r\n}\r\n}", "class i6\r\n{\r\n int p { init; }\r\n}"); TestNormalizeDeclaration("class i7\r\n{\r\nint\r\np\r\n{\r\ninit{}\r\n}\r\n}", "class i7\r\n{\r\n int p\r\n {\r\n init\r\n {\r\n }\r\n }\r\n}"); TestNormalizeDeclaration("class i8\r\n{\r\nint\r\np\r\n{\r\nget{}\r\nset{}\r\n}\r\n}", "class i8\r\n{\r\n int p\r\n {\r\n get\r\n {\r\n }\r\n\r\n set\r\n {\r\n }\r\n }\r\n}"); TestNormalizeDeclaration("class i9\r\n{\r\nint\r\np\r\n{\r\nget=>1;\r\nset{z=1;}\r\n}\r\n}", "class i9\r\n{\r\n int p\r\n {\r\n get => 1;\r\n set\r\n {\r\n z = 1;\r\n }\r\n }\r\n}"); TestNormalizeDeclaration("class ia\r\n{\r\nint\r\np\r\n{\r\nget{}\r\nset;\r\n}\r\n}", "class ia\r\n{\r\n int p\r\n {\r\n get\r\n {\r\n }\r\n\r\n set;\r\n }\r\n}"); TestNormalizeDeclaration("class ib\r\n{\r\nint\r\np\r\n{\r\nget;\r\nset{}\r\n}\r\n}", "class ib\r\n{\r\n int p\r\n {\r\n get;\r\n set\r\n {\r\n }\r\n }\r\n}"); // properties with initializers TestNormalizeDeclaration("class i4\r\n{\r\nint\r\np\r\n{\r\nset;\r\n}=1;\r\n}", "class i4\r\n{\r\n int p { set; } = 1;\r\n}"); TestNormalizeDeclaration("class i5\r\n{\r\nint\r\np\r\n{\r\nset{}\r\n}=1;\r\n}", "class i5\r\n{\r\n int p\r\n {\r\n set\r\n {\r\n }\r\n } = 1;\r\n}"); TestNormalizeDeclaration("class i6\r\n{\r\nint\r\np\r\n{\r\ninit;\r\n}=1;\r\n}", "class i6\r\n{\r\n int p { init; } = 1;\r\n}"); TestNormalizeDeclaration("class i7\r\n{\r\nint\r\np\r\n{\r\ninit{}\r\n}=1;\r\n}", "class i7\r\n{\r\n int p\r\n {\r\n init\r\n {\r\n }\r\n } = 1;\r\n}"); TestNormalizeDeclaration("class i8\r\n{\r\nint\r\np\r\n{\r\nget{}\r\nset{}\r\n}=1;\r\n}", "class i8\r\n{\r\n int p\r\n {\r\n get\r\n {\r\n }\r\n\r\n set\r\n {\r\n }\r\n } = 1;\r\n}"); TestNormalizeDeclaration("class i9\r\n{\r\nint\r\np\r\n{\r\nget=>1;\r\nset{z=1;}\r\n}=1;\r\n}", "class i9\r\n{\r\n int p\r\n {\r\n get => 1;\r\n set\r\n {\r\n z = 1;\r\n }\r\n } = 1;\r\n}"); TestNormalizeDeclaration("class ia\r\n{\r\nint\r\np\r\n{\r\nget{}\r\nset;\r\n}=1;\r\n}", "class ia\r\n{\r\n int p\r\n {\r\n get\r\n {\r\n }\r\n\r\n set;\r\n } = 1;\r\n}"); TestNormalizeDeclaration("class ib\r\n{\r\nint\r\np\r\n{\r\nget;\r\nset{}\r\n}=1;\r\n}", "class ib\r\n{\r\n int p\r\n {\r\n get;\r\n set\r\n {\r\n }\r\n } = 1;\r\n}"); // indexers TestNormalizeDeclaration("class a{b this[c d]{get;}}", "class a\r\n{\r\n b this[c d] { get; }\r\n}"); TestNormalizeDeclaration("class i1\r\n{\r\nint\r\nthis[b c]\r\n{\r\nget;\r\n}\r\n}", "class i1\r\n{\r\n int this[b c] { get; }\r\n}"); TestNormalizeDeclaration("class i2\r\n{\r\nint\r\nthis[b c]\r\n{\r\nget=>1;\r\n}\r\n}", "class i2\r\n{\r\n int this[b c] { get => 1; }\r\n}"); TestNormalizeDeclaration("class i3\r\n{\r\nint\r\nthis[b c]\r\n{\r\nget{}\r\n}\r\n}", "class i3\r\n{\r\n int this[b c]\r\n {\r\n get\r\n {\r\n }\r\n }\r\n}"); TestNormalizeDeclaration("class i4\r\n{\r\nint\r\nthis[b c]\r\n{\r\nset;\r\n}\r\n}", "class i4\r\n{\r\n int this[b c] { set; }\r\n}"); TestNormalizeDeclaration("class i5\r\n{\r\nint\r\nthis[b c]\r\n{\r\nset{}\r\n}\r\n}", "class i5\r\n{\r\n int this[b c]\r\n {\r\n set\r\n {\r\n }\r\n }\r\n}"); TestNormalizeDeclaration("class i6\r\n{\r\nint\r\nthis[b c]\r\n{\r\ninit;\r\n}\r\n}", "class i6\r\n{\r\n int this[b c] { init; }\r\n}"); TestNormalizeDeclaration("class i7\r\n{\r\nint\r\nthis[b c]\r\n{\r\ninit{}\r\n}\r\n}", "class i7\r\n{\r\n int this[b c]\r\n {\r\n init\r\n {\r\n }\r\n }\r\n}"); TestNormalizeDeclaration("class i8\r\n{\r\nint\r\nthis[b c]\r\n{\r\nget{}\r\nset{}\r\n}\r\n}", "class i8\r\n{\r\n int this[b c]\r\n {\r\n get\r\n {\r\n }\r\n\r\n set\r\n {\r\n }\r\n }\r\n}"); TestNormalizeDeclaration("class i9\r\n{\r\nint\r\nthis[b c]\r\n{\r\nget=>1;\r\nset{z=1;}\r\n}\r\n}", "class i9\r\n{\r\n int this[b c]\r\n {\r\n get => 1;\r\n set\r\n {\r\n z = 1;\r\n }\r\n }\r\n}"); TestNormalizeDeclaration("class ia\r\n{\r\nint\r\nthis[b c]\r\n{\r\nget{}\r\nset;\r\n}\r\n}", "class ia\r\n{\r\n int this[b c]\r\n {\r\n get\r\n {\r\n }\r\n\r\n set;\r\n }\r\n}"); TestNormalizeDeclaration("class ib\r\n{\r\nint\r\nthis[b c]\r\n{\r\nget;\r\nset{}\r\n}\r\n}", "class ib\r\n{\r\n int this[b c]\r\n {\r\n get;\r\n set\r\n {\r\n }\r\n }\r\n}"); // events TestNormalizeDeclaration("class a\r\n{\r\npublic\r\nevent\r\nw\r\ne;\r\n}", "class a\r\n{\r\n public event w e;\r\n}"); TestNormalizeDeclaration("abstract class b\r\n{\r\nevent\r\nw\r\ne\r\n;\r\n}", "abstract class b\r\n{\r\n event w e;\r\n}"); TestNormalizeDeclaration("interface c1\r\n{\r\nevent\r\nw\r\ne\r\n;\r\n}", "interface c1\r\n{\r\n event w e;\r\n}"); TestNormalizeDeclaration("interface c2 : c1\r\n{\r\nabstract\r\nevent\r\nw\r\nc1\r\n.\r\ne\r\n;\r\n}", "interface c2 : c1\r\n{\r\n abstract event w c1.e;\r\n}"); TestNormalizeDeclaration("class d\r\n{\r\nevent w x;\r\nevent\r\nw\r\ne\r\n{\r\nadd\r\n=>\r\nx+=\r\nvalue;\r\nremove\r\n=>x\r\n-=\r\nvalue;\r\n}}", "class d\r\n{\r\n event w x;\r\n event w e { add => x += value; remove => x -= value; }\r\n}"); TestNormalizeDeclaration("class e\r\n{\r\nevent w e\r\n{\r\nadd{}\r\nremove{\r\n}\r\n}\r\n}", "class e\r\n{\r\n event w e\r\n {\r\n add\r\n {\r\n }\r\n\r\n remove\r\n {\r\n }\r\n }\r\n}"); TestNormalizeDeclaration("class f\r\n{\r\nevent w x;\r\nevent w e\r\n{\r\nadd\r\n{\r\nx\r\n+=\r\nvalue;\r\n}\r\nremove\r\n{\r\nx\r\n-=\r\nvalue;\r\n}\r\n}\r\n}", "class f\r\n{\r\n event w x;\r\n event w e\r\n {\r\n add\r\n {\r\n x += value;\r\n }\r\n\r\n remove\r\n {\r\n x -= value;\r\n }\r\n }\r\n}"); TestNormalizeDeclaration("class g\r\n{\r\nextern\r\nevent\r\nw\r\ne\r\n=\r\nnull\r\n;\r\n}", "class g\r\n{\r\n extern event w e = null;\r\n}"); TestNormalizeDeclaration("class h\r\n{\r\npublic event w e\r\n{\r\nadd\r\n=>\r\nc\r\n(\r\n);\r\nremove\r\n=>\r\nd(\r\n);\r\n}\r\n}", "class h\r\n{\r\n public event w e { add => c(); remove => d(); }\r\n}"); TestNormalizeDeclaration("class i\r\n{\r\nevent w e\r\n{\r\nadd;\r\nremove;\r\n}\r\n}", "class i\r\n{\r\n event w e { add; remove; }\r\n}"); // fields TestNormalizeDeclaration("class a{b c;}", "class a\r\n{\r\n b c;\r\n}"); TestNormalizeDeclaration("class a{b c=d;}", "class a\r\n{\r\n b c = d;\r\n}"); TestNormalizeDeclaration("class a{b c=d,e=f;}", "class a\r\n{\r\n b c = d, e = f;\r\n}"); // delegate TestNormalizeDeclaration("delegate a b();", "delegate a b();"); TestNormalizeDeclaration("delegate a b(c);", "delegate a b(c);"); TestNormalizeDeclaration("delegate a b(c,d);", "delegate a b(c, d);"); // enums TestNormalizeDeclaration("enum a{}", "enum a\r\n{\r\n}"); TestNormalizeDeclaration("enum a{b}", "enum a\r\n{\r\n b\r\n}"); TestNormalizeDeclaration("enum a{b,c}", "enum a\r\n{\r\n b,\r\n c\r\n}"); TestNormalizeDeclaration("enum a{b=c}", "enum a\r\n{\r\n b = c\r\n}"); // attributes TestNormalizeDeclaration("[a]class b{}", "[a]\r\nclass b\r\n{\r\n}"); TestNormalizeDeclaration("\t[a]class b{}", "[a]\r\nclass b\r\n{\r\n}"); TestNormalizeDeclaration("[a,b]class c{}", "[a, b]\r\nclass c\r\n{\r\n}"); TestNormalizeDeclaration("[a(b)]class c{}", "[a(b)]\r\nclass c\r\n{\r\n}"); TestNormalizeDeclaration("[a(b,c)]class d{}", "[a(b, c)]\r\nclass d\r\n{\r\n}"); TestNormalizeDeclaration("[a][b]class c{}", "[a]\r\n[b]\r\nclass c\r\n{\r\n}"); TestNormalizeDeclaration("[a:b]class c{}", "[a: b]\r\nclass c\r\n{\r\n}"); // parameter attributes TestNormalizeDeclaration("class c{void M([a]int x,[b] [c,d]int y){}}", "class c\r\n{\r\n void M([a] int x, [b][c, d] int y)\r\n {\r\n }\r\n}"); } [Fact] public void TestFileScopedNamespace() { TestNormalizeDeclaration("namespace NS;class C{}", "namespace NS;\r\nclass C\r\n{\r\n}"); } [Fact] public void TestSpacingOnRecord() { TestNormalizeDeclaration("record class C(int I, int J);", "record class C(int I, int J);"); TestNormalizeDeclaration("record struct S(int I, int J);", "record struct S(int I, int J);"); } [Fact] [WorkItem(23618, "https://github.com/dotnet/roslyn/issues/23618")] public void TestSpacingOnInvocationLikeKeywords() { // no space between typeof and ( TestNormalizeExpression("typeof (T)", "typeof(T)"); // no space between sizeof and ( TestNormalizeExpression("sizeof (T)", "sizeof(T)"); // no space between default and ( TestNormalizeExpression("default (T)", "default(T)"); // no space between new and ( // newline between > and where TestNormalizeDeclaration( "class C<T> where T : new() { }", "class C<T>\r\n where T : new()\r\n{\r\n}"); // no space between this and ( TestNormalizeDeclaration( "class C { C() : this () { } }", "class C\r\n{\r\n C() : this()\r\n {\r\n }\r\n}"); // no space between base and ( TestNormalizeDeclaration( "class C { C() : base () { } }", "class C\r\n{\r\n C() : base()\r\n {\r\n }\r\n}"); // no space between checked and ( TestNormalizeExpression("checked (a)", "checked(a)"); // no space between unchecked and ( TestNormalizeExpression("unchecked (a)", "unchecked(a)"); // no space between __arglist and ( TestNormalizeExpression("__arglist (a)", "__arglist(a)"); } [Fact] [WorkItem(24454, "https://github.com/dotnet/roslyn/issues/24454")] public void TestSpacingOnInterpolatedString() { TestNormalizeExpression("$\"{3:C}\"", "$\"{3:C}\""); TestNormalizeExpression("$\"{3: C}\"", "$\"{3: C}\""); } [Fact] [WorkItem(23618, "https://github.com/dotnet/roslyn/issues/23618")] public void TestSpacingOnMethodConstraint() { // newline between ) and where TestNormalizeDeclaration( "class C { void M<T>() where T : struct { } }", "class C\r\n{\r\n void M<T>()\r\n where T : struct\r\n {\r\n }\r\n}"); } [WorkItem(541684, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541684")] [Fact] public void TestNormalizeRegion1() { // NOTE: the space after the region name is retained, since the text after the space // following "#region" is a single, unstructured trivia element. TestNormalizeDeclaration( "\r\nclass Class \r\n{ \r\n#region Methods \r\nvoid Method() \r\n{ \r\n} \r\n#endregion \r\n}", "class Class\r\n{\r\n#region Methods \r\n void Method()\r\n {\r\n }\r\n#endregion\r\n}"); TestNormalizeDeclaration( "\r\n#region\r\n#endregion", "#region\r\n#endregion\r\n"); TestNormalizeDeclaration( "\r\n#region \r\n#endregion", "#region\r\n#endregion\r\n"); TestNormalizeDeclaration( "\r\n#region name //comment\r\n#endregion", "#region name //comment\r\n#endregion\r\n"); TestNormalizeDeclaration( "\r\n#region /*comment*/\r\n#endregion", "#region /*comment*/\r\n#endregion\r\n"); } [WorkItem(2076, "github")] [Fact] public void TestNormalizeInterpolatedString() { TestNormalizeExpression(@"$""Message is {a}""", @"$""Message is {a}"""); } [WorkItem(528584, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528584")] [Fact] public void TestNormalizeRegion2() { TestNormalizeDeclaration( "\r\n#region //comment\r\n#endregion", // NOTE: the extra newline should be removed, but it's not worth the // effort (see DevDiv #8564) "#region //comment\r\n\r\n#endregion\r\n"); TestNormalizeDeclaration( "\r\n#region //comment\r\n\r\n#endregion", // NOTE: the extra newline should be removed, but it's not worth the // effort (see DevDiv #8564). "#region //comment\r\n\r\n#endregion\r\n"); } private void TestNormalizeDeclaration(string text, string expected) { var node = SyntaxFactory.ParseCompilationUnit(text); Assert.Equal(text.NormalizeLineEndings(), node.ToFullString().NormalizeLineEndings()); var actual = node.NormalizeWhitespace(" ").ToFullString(); Assert.Equal(expected.NormalizeLineEndings(), actual.NormalizeLineEndings()); } [Fact] public void TestNormalizeComments() { TestNormalizeToken("a//b", "a //b\r\n"); TestNormalizeToken("a/*b*/", "a /*b*/"); TestNormalizeToken("//a\r\nb", "//a\r\nb"); TestNormalizeExpression("a/*b*/+c", "a /*b*/ + c"); TestNormalizeExpression("/*a*/b", "/*a*/\r\nb"); TestNormalizeExpression("/*a\r\n*/b", "/*a\r\n*/\r\nb"); TestNormalizeStatement("{/*a*/b}", "{ /*a*/\r\n b\r\n}"); TestNormalizeStatement("{\r\na//b\r\n}", "{\r\n a //b\r\n}"); TestNormalizeStatement("{\r\n//a\r\n}", "{\r\n//a\r\n}"); TestNormalizeStatement("{\r\n//a\r\nb}", "{\r\n //a\r\n b\r\n}"); TestNormalizeStatement("{\r\n/*a*/b}", "{\r\n /*a*/\r\n b\r\n}"); TestNormalizeStatement("{\r\n/// <goo/>\r\na}", "{\r\n /// <goo/>\r\n a\r\n}"); TestNormalizeStatement("{\r\n///<goo/>\r\na}", "{\r\n ///<goo/>\r\n a\r\n}"); TestNormalizeStatement("{\r\n/// <goo>\r\n/// </goo>\r\na}", "{\r\n /// <goo>\r\n /// </goo>\r\n a\r\n}"); TestNormalizeToken("/// <goo>\r\n/// </goo>\r\na", "/// <goo>\r\n/// </goo>\r\na"); TestNormalizeStatement("{\r\n/*** <goo/> ***/\r\na}", "{\r\n /*** <goo/> ***/\r\n a\r\n}"); TestNormalizeStatement("{\r\n/*** <goo/>\r\n ***/\r\na}", "{\r\n /*** <goo/>\r\n ***/\r\n a\r\n}"); } private void TestNormalizeToken(string text, string expected) { var token = SyntaxFactory.ParseToken(text); var actual = token.NormalizeWhitespace().ToFullString(); Assert.Equal(expected, actual); } [Fact] [WorkItem(1066, "github")] public void TestNormalizePreprocessorDirectives() { // directive as node TestNormalize(SyntaxFactory.DefineDirectiveTrivia(SyntaxFactory.Identifier("a"), false), "#define a\r\n"); // directive as trivia TestNormalizeTrivia(" # define a", "#define a\r\n"); TestNormalizeTrivia("#if(a||b)", "#if (a || b)\r\n"); TestNormalizeTrivia("#if(a&&b)", "#if (a && b)\r\n"); TestNormalizeTrivia(" #if a\r\n #endif", "#if a\r\n#endif\r\n"); TestNormalize( SyntaxFactory.TriviaList( SyntaxFactory.Trivia( SyntaxFactory.IfDirectiveTrivia(SyntaxFactory.IdentifierName("a"), false, false, false)), SyntaxFactory.Trivia( SyntaxFactory.EndIfDirectiveTrivia(false))), "#if a\r\n#endif\r\n"); TestNormalizeTrivia("#endregion goo", "#endregion goo\r\n"); TestNormalizeDeclaration( @"#pragma warning disable 123 namespace goo { } #pragma warning restore 123", @"#pragma warning disable 123 namespace goo { } #pragma warning restore 123 "); } [Fact] [WorkItem(531607, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531607")] public void TestNormalizeLineDirectiveTrivia() { TestNormalize( SyntaxFactory.TriviaList( SyntaxFactory.Trivia( SyntaxFactory.LineDirectiveTrivia( SyntaxFactory.Literal(1), true) .WithEndOfDirectiveToken( SyntaxFactory.Token( SyntaxFactory.TriviaList( SyntaxFactory.Trivia( SyntaxFactory.SkippedTokensTrivia() .WithTokens( SyntaxFactory.TokenList( SyntaxFactory.Literal(@"""a\b"""))))), SyntaxKind.EndOfDirectiveToken, default(SyntaxTriviaList))))), @"#line 1 ""\""a\\b\"""" "); // Note: without all the escaping, it looks like this '#line 1 @"""a\b"""' (i.e. the string literal has a value of '"a\b"'). // Note: the literal was formatted as a C# string literal, not as a directive string literal. } [WorkItem(538115, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538115")] [Fact] public void TestNormalizeWithinDirectives() { TestNormalizeDeclaration( "class C\r\n{\r\n#if true\r\nvoid Goo(A x) { }\r\n#else\r\n#endif\r\n}\r\n", "class C\r\n{\r\n#if true\r\n void Goo(A x)\r\n {\r\n }\r\n#else\r\n#endif\r\n}"); } [WorkItem(542887, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542887")] [Fact] public void TestFormattingForBlockSyntax() { var code = @"class c1 { void goo() { { int i = 1; } } }"; var tree = SyntaxFactory.ParseSyntaxTree(code); TestNormalize(tree.GetCompilationUnitRoot(), @"class c1 { void goo() { { int i = 1; } } }".NormalizeLineEndings()); } [WorkItem(1079042, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1079042")] [Fact] public void TestNormalizeDocumentationComments() { var code = @"class c1 { ///<summary> /// A documentation comment ///</summary> void goo() { } }"; var tree = SyntaxFactory.ParseSyntaxTree(code); TestNormalize(tree.GetCompilationUnitRoot(), "class c1\r\n" + "{\r\n" + // The normalizer doesn't change line endings in comments, // see https://github.com/dotnet/roslyn/issues/8536 $" ///<summary>{Environment.NewLine}" + $" /// A documentation comment{Environment.NewLine}" + $" ///</summary>{Environment.NewLine}" + " void goo()\r\n" + " {\r\n" + " }\r\n" + "}"); } [Fact] public void TestNormalizeDocumentationComments2() { var code = @"class c1 { /// <summary> /// A documentation comment /// </summary> void goo() { } }"; var tree = SyntaxFactory.ParseSyntaxTree(code); TestNormalize(tree.GetCompilationUnitRoot(), "class c1\r\n" + "{\r\n" + // The normalizer doesn't change line endings in comments, // see https://github.com/dotnet/roslyn/issues/8536 $" /// <summary>{Environment.NewLine}" + $" /// A documentation comment{Environment.NewLine}" + $" /// </summary>{Environment.NewLine}" + " void goo()\r\n" + " {\r\n" + " }\r\n" + "}"); } [Fact] public void TestNormalizeEOL() { var code = "class c{}"; var expected = "class c\n{\n}"; var actual = SyntaxFactory.ParseCompilationUnit(code).NormalizeWhitespace(indentation: " ", eol: "\n").ToFullString(); Assert.Equal(expected, actual); } [Fact] public void TestNormalizeTabs() { var code = "class c{void m(){}}"; var expected = "class c\r\n{\r\n\tvoid m()\r\n\t{\r\n\t}\r\n}"; var actual = SyntaxFactory.ParseCompilationUnit(code).NormalizeWhitespace(indentation: "\t").ToFullString(); Assert.Equal(expected, actual); } [Fact] [WorkItem(29390, "https://github.com/dotnet/roslyn/issues/29390")] public void TestNormalizeTuples() { TestNormalizeDeclaration("new(string prefix,string uri)[10]", "new (string prefix, string uri)[10]"); TestNormalizeDeclaration("(string prefix,string uri)[]ns", "(string prefix, string uri)[] ns"); TestNormalizeDeclaration("(string prefix,(string uri,string help))ns", "(string prefix, (string uri, string help)) ns"); TestNormalizeDeclaration("(string prefix,string uri)ns", "(string prefix, string uri) ns"); TestNormalizeDeclaration("public void Foo((string prefix,string uri)ns)", "public void Foo((string prefix, string uri) ns)"); TestNormalizeDeclaration("public (string prefix,string uri)Foo()", "public (string prefix, string uri) Foo()"); } [Fact] [WorkItem(50664, "https://github.com/dotnet/roslyn/issues/50664")] public void TestNormalizeFunctionPointer() { var content = @"unsafe class C { delegate * < int , int > functionPointer; }"; var expected = @"unsafe class C { delegate*<int, int> functionPointer; }"; TestNormalizeDeclaration(content, expected); } [Fact] [WorkItem(50664, "https://github.com/dotnet/roslyn/issues/50664")] public void TestNormalizeFunctionPointerWithManagedCallingConvention() { var content = @"unsafe class C { delegate *managed < int , int > functionPointer; }"; var expected = @"unsafe class C { delegate* managed<int, int> functionPointer; }"; TestNormalizeDeclaration(content, expected); } [Fact] [WorkItem(50664, "https://github.com/dotnet/roslyn/issues/50664")] public void TestNormalizeFunctionPointerWithUnmanagedCallingConvention() { var content = @"unsafe class C { delegate *unmanaged < int , int > functionPointer; }"; var expected = @"unsafe class C { delegate* unmanaged<int, int> functionPointer; }"; TestNormalizeDeclaration(content, expected); } [Fact] [WorkItem(50664, "https://github.com/dotnet/roslyn/issues/50664")] public void TestNormalizeFunctionPointerWithUnmanagedCallingConventionAndSpecifiers() { var content = @"unsafe class C { delegate *unmanaged [ Cdecl , Thiscall ] < int , int > functionPointer; }"; var expected = @"unsafe class C { delegate* unmanaged[Cdecl, Thiscall]<int, int> functionPointer; }"; TestNormalizeDeclaration(content, expected); } [Fact] [WorkItem(53254, "https://github.com/dotnet/roslyn/issues/53254")] public void TestNormalizeColonInConstructorInitializer() { var content = @"class Base { } class Derived : Base { public Derived():base(){} }"; var expected = @"class Base { } class Derived : Base { public Derived() : base() { } }"; TestNormalizeDeclaration(content, expected); } [Fact] [WorkItem(49732, "https://github.com/dotnet/roslyn/issues/49732")] public void TestNormalizeXmlInDocComment() { var code = @"/// <returns> /// If this method succeeds, it returns <b xmlns:loc=""http://microsoft.com/wdcml/l10n"">S_OK</b>. /// </returns>"; TestNormalizeDeclaration(code, code); } [Theory] [InlineData("_=()=>{};", "_ = () =>\r\n{\r\n};")] [InlineData("_=x=>{};", "_ = x =>\r\n{\r\n};")] [InlineData("Add(()=>{});", "Add(() =>\r\n{\r\n});")] [InlineData("Add(delegate(){});", "Add(delegate ()\r\n{\r\n});")] [InlineData("Add(()=>{{_=x=>{};}});", "Add(() =>\r\n{\r\n {\r\n _ = x =>\r\n {\r\n };\r\n }\r\n});")] [WorkItem(46656, "https://github.com/dotnet/roslyn/issues/46656")] public void TestNormalizeBlockAnonymousFunctions(string actual, string expected) { TestNormalizeStatement(actual, expected); } [Fact] public void TestNormalizeExtendedPropertyPattern() { var text = "_ = this is{Property . Property :2};"; var expected = @"_ = this is { Property.Property: 2 };"; TestNormalizeStatement(text, expected); } private void TestNormalize(CSharpSyntaxNode node, string expected) { var actual = node.NormalizeWhitespace(" ").ToFullString(); Assert.Equal(expected, actual); } private void TestNormalizeTrivia(string text, string expected) { var list = SyntaxFactory.ParseLeadingTrivia(text); TestNormalize(list, expected); } private void TestNormalize(SyntaxTriviaList trivia, string expected) { var actual = trivia.NormalizeWhitespace(" ").ToFullString().NormalizeLineEndings(); Assert.Equal(expected.NormalizeLineEndings(), actual); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Text; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; using System; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class SyntaxNormalizerTests { [Fact, WorkItem(52543, "https://github.com/dotnet/roslyn/issues/52543")] public void TestNormalizePatternInIf() { TestNormalizeStatement( @"{object x = 1; if (x is {}) { } if (x is {} t) { } if (x is int {} t2) { } if (x is System.ValueTuple<int, int>(_, _) { Item1: > 10 } t3) { } if (x is System.ValueTuple<int, int>(_, _) { Item1: > 10, Item2: < 20 }) { } }", @"{ object x = 1; if (x is { }) { } if (x is { } t) { } if (x is int { } t2) { } if (x is System.ValueTuple<int, int> (_, _) { Item1: > 10 } t3) { } if (x is System.ValueTuple<int, int> (_, _) { Item1: > 10, Item2: < 20 }) { } }".NormalizeLineEndings() ); } [Fact, WorkItem(52543, "https://github.com/dotnet/roslyn/issues/52543")] public void TestNormalizeSwitchExpression() { TestNormalizeStatement( @"var x = (int)1 switch { 1 => ""one"", 2 => ""two"", 3 => ""three"", {} => "">= 4"" };", @"var x = (int)1 switch { 1 => ""one"", 2 => ""two"", 3 => ""three"", { } => "">= 4"" };".NormalizeLineEndings() ); } [Fact, WorkItem(52543, "https://github.com/dotnet/roslyn/issues/52543")] public void TestNormalizeSwitchRecPattern() { TestNormalizeStatement( @"var x = (object)1 switch { int { } => ""two"", { } t when t.GetHashCode() == 42 => ""42"", System.ValueTuple<int, int> (1, _) { Item2: > 2 and < 20 } => ""tuple.Item2 < 20"", System.ValueTuple<int, int> (1, _) { Item2: >= 100 } greater => greater.ToString(), System.ValueType {} => ""not null value"", object {} i when i is not 42 => ""not 42"", { } => ""not null"", null => ""null"", };", @"var x = (object)1 switch { int { } => ""two"", { } t when t.GetHashCode() == 42 => ""42"", System.ValueTuple<int, int> (1, _) { Item2: > 2 and < 20 } => ""tuple.Item2 < 20"", System.ValueTuple<int, int> (1, _) { Item2: >= 100 } greater => greater.ToString(), System.ValueType { } => ""not null value"", object { } i when i is not 42 => ""not 42"", { } => ""not null"", null => ""null"", };".NormalizeLineEndings() ); } [Fact, WorkItem(52543, "https://github.com/dotnet/roslyn/issues/52543")] public void TestNormalizeSwitchExpressionComplex() { var a = @"var x = vehicle switch { Car { Passengers: 0 } => 2.00m + 0.50m, Car { Passengers: 1 } => 2.0m, Car { Passengers: 2 } => 2.0m - 0.50m, Car c => 2.00m - 1.0m, Taxi { Fares: 0 } => 3.50m + 1.00m, Taxi { Fares: 1 } => 3.50m, Taxi { Fares: 2 } => 3.50m - 0.50m, Taxi t => 3.50m - 1.00m, Bus b when ((double)b.Riders / (double)b.Capacity) < 0.50 => 5.00m + 2.00m, Bus b when ((double)b.Riders / (double)b.Capacity) > 0.90 => 5.00m - 1.00m, Bus b => 5.00m, DeliveryTruck t when (t.GrossWeightClass > 5000) => 10.00m + 5.00m, DeliveryTruck t when (t.GrossWeightClass < 3000) => 10.00m - 2.00m, DeliveryTruck t => 10.00m, { } => -1, //throw new ArgumentException(message: ""Not a known vehicle type"", paramName: nameof(vehicle)), null => 0//throw new ArgumentNullException(nameof(vehicle)) };"; var b = @"var x = vehicle switch { Car { Passengers: 0 } => 2.00m + 0.50m, Car { Passengers: 1 } => 2.0m, Car { Passengers: 2 } => 2.0m - 0.50m, Car c => 2.00m - 1.0m, Taxi { Fares: 0 } => 3.50m + 1.00m, Taxi { Fares: 1 } => 3.50m, Taxi { Fares: 2 } => 3.50m - 0.50m, Taxi t => 3.50m - 1.00m, Bus b when ((double)b.Riders / (double)b.Capacity) < 0.50 => 5.00m + 2.00m, Bus b when ((double)b.Riders / (double)b.Capacity) > 0.90 => 5.00m - 1.00m, Bus b => 5.00m, DeliveryTruck t when (t.GrossWeightClass > 5000) => 10.00m + 5.00m, DeliveryTruck t when (t.GrossWeightClass < 3000) => 10.00m - 2.00m, DeliveryTruck t => 10.00m, { } => -1, //throw new ArgumentException(message: ""Not a known vehicle type"", paramName: nameof(vehicle)), null => 0 //throw new ArgumentNullException(nameof(vehicle)) };".NormalizeLineEndings(); TestNormalizeStatement(a, b); } [Fact, WorkItem(50742, "https://github.com/dotnet/roslyn/issues/50742")] public void TestLineBreakInterpolations() { TestNormalizeExpression( @"$""Printed: { new Printer() { TextToPrint = ""Hello world!"" }.PrintedText }""", @"$""Printed: {new Printer(){TextToPrint = ""Hello world!""}.PrintedText}""" ); } [Fact, WorkItem(50742, "https://github.com/dotnet/roslyn/issues/50742")] public void TestVerbatimStringInterpolationWithLineBreaks() { TestNormalizeStatement(@"Console.WriteLine($@""Test with line breaks { new[]{ 1, 2, 3 }[2] } "");", @"Console.WriteLine($@""Test with line breaks {new[]{1, 2, 3}[2]} "");" ); } [Fact] public void TestNormalizeExpression1() { TestNormalizeExpression("!a", "!a"); TestNormalizeExpression("-a", "-a"); TestNormalizeExpression("+a", "+a"); TestNormalizeExpression("~a", "~a"); TestNormalizeExpression("a", "a"); TestNormalizeExpression("a+b", "a + b"); TestNormalizeExpression("a-b", "a - b"); TestNormalizeExpression("a*b", "a * b"); TestNormalizeExpression("a/b", "a / b"); TestNormalizeExpression("a%b", "a % b"); TestNormalizeExpression("a^b", "a ^ b"); TestNormalizeExpression("a|b", "a | b"); TestNormalizeExpression("a&b", "a & b"); TestNormalizeExpression("a||b", "a || b"); TestNormalizeExpression("a&&b", "a && b"); TestNormalizeExpression("a<b", "a < b"); TestNormalizeExpression("a<=b", "a <= b"); TestNormalizeExpression("a>b", "a > b"); TestNormalizeExpression("a>=b", "a >= b"); TestNormalizeExpression("a==b", "a == b"); TestNormalizeExpression("a!=b", "a != b"); TestNormalizeExpression("a<<b", "a << b"); TestNormalizeExpression("a>>b", "a >> b"); TestNormalizeExpression("a??b", "a ?? b"); TestNormalizeExpression("a<b>.c", "a<b>.c"); TestNormalizeExpression("(a+b)", "(a + b)"); TestNormalizeExpression("((a)+(b))", "((a) + (b))"); TestNormalizeExpression("(a)b", "(a)b"); TestNormalizeExpression("(a)(b)", "(a)(b)"); TestNormalizeExpression("m()", "m()"); TestNormalizeExpression("m(a)", "m(a)"); TestNormalizeExpression("m(a,b)", "m(a, b)"); TestNormalizeExpression("m(a,b,c)", "m(a, b, c)"); TestNormalizeExpression("m(a,b(c,d))", "m(a, b(c, d))"); TestNormalizeExpression("a?b:c", "a ? b : c"); TestNormalizeExpression("from a in b where c select d", "from a in b\r\nwhere c\r\nselect d"); TestNormalizeExpression("a().b().c()", "a().b().c()"); TestNormalizeExpression("a->b->c", "a->b->c"); TestNormalizeExpression("global :: a", "global::a"); TestNormalizeExpression("(IList<int>)args", "(IList<int>)args"); TestNormalizeExpression("(IList<IList<int>>)args", "(IList<IList<int>>)args"); TestNormalizeExpression("(IList<string?>)args", "(IList<string?>)args"); } private void TestNormalizeExpression(string text, string expected) { var node = SyntaxFactory.ParseExpression(text); var actual = node.NormalizeWhitespace(" ").ToFullString(); Assert.Equal(expected, actual); } [Fact] public void TestNormalizeStatement1() { // expressions TestNormalizeStatement("a;", "a;"); // blocks TestNormalizeStatement("{a;}", "{\r\n a;\r\n}"); TestNormalizeStatement("{a;b;}", "{\r\n a;\r\n b;\r\n}"); TestNormalizeStatement("\t{a;}", "{\r\n a;\r\n}"); TestNormalizeStatement("\t{a;b;}", "{\r\n a;\r\n b;\r\n}"); // if TestNormalizeStatement("if(a)b;", "if (a)\r\n b;"); TestNormalizeStatement("if(a){b;}", "if (a)\r\n{\r\n b;\r\n}"); TestNormalizeStatement("if(a){b;c;}", "if (a)\r\n{\r\n b;\r\n c;\r\n}"); TestNormalizeStatement("if(a)b;else c;", "if (a)\r\n b;\r\nelse\r\n c;"); TestNormalizeStatement("if(a)b;else if(c)d;", "if (a)\r\n b;\r\nelse if (c)\r\n d;"); // while TestNormalizeStatement("while(a)b;", "while (a)\r\n b;"); TestNormalizeStatement("while(a){b;}", "while (a)\r\n{\r\n b;\r\n}"); // do TestNormalizeStatement("do{a;}while(b);", "do\r\n{\r\n a;\r\n}\r\nwhile (b);"); // for TestNormalizeStatement("for(a;b;c)d;", "for (a; b; c)\r\n d;"); TestNormalizeStatement("for(;;)a;", "for (;;)\r\n a;"); // foreach TestNormalizeStatement("foreach(a in b)c;", "foreach (a in b)\r\n c;"); // try TestNormalizeStatement("try{a;}catch(b){c;}", "try\r\n{\r\n a;\r\n}\r\ncatch (b)\r\n{\r\n c;\r\n}"); TestNormalizeStatement("try{a;}finally{b;}", "try\r\n{\r\n a;\r\n}\r\nfinally\r\n{\r\n b;\r\n}"); // other TestNormalizeStatement("lock(a)b;", "lock (a)\r\n b;"); TestNormalizeStatement("fixed(a)b;", "fixed (a)\r\n b;"); TestNormalizeStatement("using(a)b;", "using (a)\r\n b;"); TestNormalizeStatement("checked{a;}", "checked\r\n{\r\n a;\r\n}"); TestNormalizeStatement("unchecked{a;}", "unchecked\r\n{\r\n a;\r\n}"); TestNormalizeStatement("unsafe{a;}", "unsafe\r\n{\r\n a;\r\n}"); // declaration statements TestNormalizeStatement("a b;", "a b;"); TestNormalizeStatement("a?b;", "a? b;"); TestNormalizeStatement("a b,c;", "a b, c;"); TestNormalizeStatement("a b=c;", "a b = c;"); TestNormalizeStatement("a b=c,d=e;", "a b = c, d = e;"); // empty statements TestNormalizeStatement(";", ";"); TestNormalizeStatement("{;;}", "{\r\n ;\r\n ;\r\n}"); // labelled statements TestNormalizeStatement("goo:;", "goo:\r\n ;"); TestNormalizeStatement("goo:a;", "goo:\r\n a;"); // return/goto TestNormalizeStatement("return;", "return;"); TestNormalizeStatement("return(a);", "return (a);"); TestNormalizeStatement("continue;", "continue;"); TestNormalizeStatement("break;", "break;"); TestNormalizeStatement("yield return;", "yield return;"); TestNormalizeStatement("yield return(a);", "yield return (a);"); TestNormalizeStatement("yield break;", "yield break;"); TestNormalizeStatement("goto a;", "goto a;"); TestNormalizeStatement("throw;", "throw;"); TestNormalizeStatement("throw a;", "throw a;"); TestNormalizeStatement("return this.Bar()", "return this.Bar()"); // switch TestNormalizeStatement("switch(a){case b:c;}", "switch (a)\r\n{\r\n case b:\r\n c;\r\n}"); TestNormalizeStatement("switch(a){case b:c;case d:e;}", "switch (a)\r\n{\r\n case b:\r\n c;\r\n case d:\r\n e;\r\n}"); TestNormalizeStatement("switch(a){case b:c;default:d;}", "switch (a)\r\n{\r\n case b:\r\n c;\r\n default:\r\n d;\r\n}"); TestNormalizeStatement("switch(a){case b:{}default:{}}", "switch (a)\r\n{\r\n case b:\r\n {\r\n }\r\n\r\n default:\r\n {\r\n }\r\n}"); TestNormalizeStatement("switch(a){case b:c();d();default:e();f();}", "switch (a)\r\n{\r\n case b:\r\n c();\r\n d();\r\n default:\r\n e();\r\n f();\r\n}"); TestNormalizeStatement("switch(a){case b:{c();}}", "switch (a)\r\n{\r\n case b:\r\n {\r\n c();\r\n }\r\n}"); // curlies TestNormalizeStatement("{if(goo){}if(bar){}}", "{\r\n if (goo)\r\n {\r\n }\r\n\r\n if (bar)\r\n {\r\n }\r\n}"); // Queries TestNormalizeStatement("int i=from v in vals select v;", "int i =\r\n from v in vals\r\n select v;"); TestNormalizeStatement("Goo(from v in vals select v);", "Goo(\r\n from v in vals\r\n select v);"); TestNormalizeStatement("int i=from v in vals select from x in xxx where x > 10 select x;", "int i =\r\n from v in vals\r\n select\r\n from x in xxx\r\n where x > 10\r\n select x;"); TestNormalizeStatement("int i=from v in vals group v by x into g where g > 10 select g;", "int i =\r\n from v in vals\r\n group v by x into g\r\n where g > 10\r\n select g;"); // Generics TestNormalizeStatement("Func<string, int> f = blah;", "Func<string, int> f = blah;"); } [Theory] [InlineData("int*p;", "int* p;")] [InlineData("int *p;", "int* p;")] [InlineData("int*p1,p2;", "int* p1, p2;")] [InlineData("int *p1, p2;", "int* p1, p2;")] [InlineData("int**p;", "int** p;")] [InlineData("int **p;", "int** p;")] [InlineData("int**p1,p2;", "int** p1, p2;")] [InlineData("int **p1, p2;", "int** p1, p2;")] [WorkItem(49733, "https://github.com/dotnet/roslyn/issues/49733")] public void TestNormalizeAsteriskInPointerDeclaration(string text, string expected) { TestNormalizeStatement(text, expected); } [Fact] [WorkItem(49733, "https://github.com/dotnet/roslyn/issues/49733")] public void TestNormalizeAsteriskInPointerReturnTypeOfIndexer() { var text = @"public unsafe class C { int*this[int x,int y]{get=>(int*)0;} }"; var expected = @"public unsafe class C { int* this[int x, int y] { get => (int*)0; } }"; TestNormalizeDeclaration(text, expected); } [Fact] public void TestNormalizeAsteriskInVoidPointerCast() { var text = @"public unsafe class C { void*this[int x,int y]{get => ( void * ) 0;} }"; var expected = @"public unsafe class C { void* this[int x, int y] { get => (void*)0; } }"; TestNormalizeDeclaration(text, expected); } private void TestNormalizeStatement(string text, string expected) { var node = SyntaxFactory.ParseStatement(text); var actual = node.NormalizeWhitespace(" ").ToFullString(); Assert.Equal(expected, actual); } [Fact] public void TestNormalizeDeclaration1() { // usings TestNormalizeDeclaration("using a;", "using a;"); TestNormalizeDeclaration("using a=b;", "using a = b;"); TestNormalizeDeclaration("using a.b;", "using a.b;"); TestNormalizeDeclaration("using A; using B; class C {}", "using A;\r\nusing B;\r\n\r\nclass C\r\n{\r\n}"); TestNormalizeDeclaration("global using a;", "global using a;"); TestNormalizeDeclaration("global using a=b;", "global using a = b;"); TestNormalizeDeclaration("global using a.b;", "global using a.b;"); TestNormalizeDeclaration("global using A; global using B; class C {}", "global using A;\r\nglobal using B;\r\n\r\nclass C\r\n{\r\n}"); TestNormalizeDeclaration("global using A; using B; class C {}", "global using A;\r\nusing B;\r\n\r\nclass C\r\n{\r\n}"); TestNormalizeDeclaration("using A; global using B; class C {}", "using A;\r\nglobal using B;\r\n\r\nclass C\r\n{\r\n}"); // namespace TestNormalizeDeclaration("namespace a{}", "namespace a\r\n{\r\n}"); TestNormalizeDeclaration("namespace a{using b;}", "namespace a\r\n{\r\n using b;\r\n}"); TestNormalizeDeclaration("namespace a{global using b;}", "namespace a\r\n{\r\n global using b;\r\n}"); TestNormalizeDeclaration("namespace a{namespace b{}}", "namespace a\r\n{\r\n namespace b\r\n {\r\n }\r\n}"); TestNormalizeDeclaration("namespace a{}namespace b{}", "namespace a\r\n{\r\n}\r\n\r\nnamespace b\r\n{\r\n}"); // type TestNormalizeDeclaration("class a{}", "class a\r\n{\r\n}"); TestNormalizeDeclaration("class a{class b{}}", "class a\r\n{\r\n class b\r\n {\r\n }\r\n}"); TestNormalizeDeclaration("class a<b>where a:c{}", "class a<b>\r\n where a : c\r\n{\r\n}"); TestNormalizeDeclaration("class a<b,c>where a:c{}", "class a<b, c>\r\n where a : c\r\n{\r\n}"); TestNormalizeDeclaration("class a:b{}", "class a : b\r\n{\r\n}"); // methods TestNormalizeDeclaration("class a{void b(){}}", "class a\r\n{\r\n void b()\r\n {\r\n }\r\n}"); TestNormalizeDeclaration("class a{void b(){}void c(){}}", "class a\r\n{\r\n void b()\r\n {\r\n }\r\n\r\n void c()\r\n {\r\n }\r\n}"); TestNormalizeDeclaration("class a{a(){}}", "class a\r\n{\r\n a()\r\n {\r\n }\r\n}"); TestNormalizeDeclaration("class a{~a(){}}", "class a\r\n{\r\n ~a()\r\n {\r\n }\r\n}"); // properties TestNormalizeDeclaration("class a{b c{get;}}", "class a\r\n{\r\n b c { get; }\r\n}"); TestNormalizeDeclaration("class a {\r\nint X{get;set;}= 2;\r\n}\r\n", "class a\r\n{\r\n int X { get; set; } = 2;\r\n}"); TestNormalizeDeclaration("class a {\r\nint Y\r\n{get;\r\nset;\r\n}\r\n=99;\r\n}\r\n", "class a\r\n{\r\n int Y { get; set; } = 99;\r\n}"); TestNormalizeDeclaration("class a {\r\nint Z{get;}\r\n}\r\n", "class a\r\n{\r\n int Z { get; }\r\n}"); TestNormalizeDeclaration("class a {\r\nint T{get;init;}\r\nint R{get=>1;}\r\n}\r\n", "class a\r\n{\r\n int T { get; init; }\r\n\r\n int R { get => 1; }\r\n}"); TestNormalizeDeclaration("class a {\r\nint Q{get{return 0;}init{}}\r\nint R{get=>1;}\r\n}\r\n", "class a\r\n{\r\n int Q\r\n {\r\n get\r\n {\r\n return 0;\r\n }\r\n\r\n init\r\n {\r\n }\r\n }\r\n\r\n int R { get => 1; }\r\n}"); TestNormalizeDeclaration("class a {\r\nint R{get=>1;}\r\n}\r\n", "class a\r\n{\r\n int R { get => 1; }\r\n}"); TestNormalizeDeclaration("class a {\r\nint S=>2;\r\n}\r\n", "class a\r\n{\r\n int S => 2;\r\n}"); TestNormalizeDeclaration("class x\r\n{\r\nint _g;\r\nint G\r\n{\r\nget\r\n{\r\nreturn\r\n_g;\r\n}\r\ninit;\r\n}\r\nint H\r\n{\r\nget;\r\nset\r\n{\r\n_g\r\n=\r\n12;\r\n}\r\n}\r\n}\r\n", "class x\r\n{\r\n int _g;\r\n int G\r\n {\r\n get\r\n {\r\n return _g;\r\n }\r\n\r\n init;\r\n }\r\n\r\n int H\r\n {\r\n get;\r\n set\r\n {\r\n _g = 12;\r\n }\r\n }\r\n}"); TestNormalizeDeclaration("class i1\r\n{\r\nint\r\np\r\n{\r\nget;\r\n}\r\n}", "class i1\r\n{\r\n int p { get; }\r\n}"); TestNormalizeDeclaration("class i2\r\n{\r\nint\r\np\r\n{\r\nget=>2;\r\n}\r\n}", "class i2\r\n{\r\n int p { get => 2; }\r\n}"); TestNormalizeDeclaration("class i2a\r\n{\r\nint _p;\r\nint\r\np\r\n{\r\nget=>\r\n_p;set\r\n=>_p\r\n=value\r\n;\r\n}\r\n}", "class i2a\r\n{\r\n int _p;\r\n int p { get => _p; set => _p = value; }\r\n}"); TestNormalizeDeclaration("class i3\r\n{\r\nint\r\np\r\n{\r\nget{}\r\n}\r\n}", "class i3\r\n{\r\n int p\r\n {\r\n get\r\n {\r\n }\r\n }\r\n}"); TestNormalizeDeclaration("class i4\r\n{\r\nint\r\np\r\n{\r\nset;\r\n}\r\n}", "class i4\r\n{\r\n int p { set; }\r\n}"); TestNormalizeDeclaration("class i5\r\n{\r\nint\r\np\r\n{\r\nset{}\r\n}\r\n}", "class i5\r\n{\r\n int p\r\n {\r\n set\r\n {\r\n }\r\n }\r\n}"); TestNormalizeDeclaration("class i6\r\n{\r\nint\r\np\r\n{\r\ninit;\r\n}\r\n}", "class i6\r\n{\r\n int p { init; }\r\n}"); TestNormalizeDeclaration("class i7\r\n{\r\nint\r\np\r\n{\r\ninit{}\r\n}\r\n}", "class i7\r\n{\r\n int p\r\n {\r\n init\r\n {\r\n }\r\n }\r\n}"); TestNormalizeDeclaration("class i8\r\n{\r\nint\r\np\r\n{\r\nget{}\r\nset{}\r\n}\r\n}", "class i8\r\n{\r\n int p\r\n {\r\n get\r\n {\r\n }\r\n\r\n set\r\n {\r\n }\r\n }\r\n}"); TestNormalizeDeclaration("class i9\r\n{\r\nint\r\np\r\n{\r\nget=>1;\r\nset{z=1;}\r\n}\r\n}", "class i9\r\n{\r\n int p\r\n {\r\n get => 1;\r\n set\r\n {\r\n z = 1;\r\n }\r\n }\r\n}"); TestNormalizeDeclaration("class ia\r\n{\r\nint\r\np\r\n{\r\nget{}\r\nset;\r\n}\r\n}", "class ia\r\n{\r\n int p\r\n {\r\n get\r\n {\r\n }\r\n\r\n set;\r\n }\r\n}"); TestNormalizeDeclaration("class ib\r\n{\r\nint\r\np\r\n{\r\nget;\r\nset{}\r\n}\r\n}", "class ib\r\n{\r\n int p\r\n {\r\n get;\r\n set\r\n {\r\n }\r\n }\r\n}"); // properties with initializers TestNormalizeDeclaration("class i4\r\n{\r\nint\r\np\r\n{\r\nset;\r\n}=1;\r\n}", "class i4\r\n{\r\n int p { set; } = 1;\r\n}"); TestNormalizeDeclaration("class i5\r\n{\r\nint\r\np\r\n{\r\nset{}\r\n}=1;\r\n}", "class i5\r\n{\r\n int p\r\n {\r\n set\r\n {\r\n }\r\n } = 1;\r\n}"); TestNormalizeDeclaration("class i6\r\n{\r\nint\r\np\r\n{\r\ninit;\r\n}=1;\r\n}", "class i6\r\n{\r\n int p { init; } = 1;\r\n}"); TestNormalizeDeclaration("class i7\r\n{\r\nint\r\np\r\n{\r\ninit{}\r\n}=1;\r\n}", "class i7\r\n{\r\n int p\r\n {\r\n init\r\n {\r\n }\r\n } = 1;\r\n}"); TestNormalizeDeclaration("class i8\r\n{\r\nint\r\np\r\n{\r\nget{}\r\nset{}\r\n}=1;\r\n}", "class i8\r\n{\r\n int p\r\n {\r\n get\r\n {\r\n }\r\n\r\n set\r\n {\r\n }\r\n } = 1;\r\n}"); TestNormalizeDeclaration("class i9\r\n{\r\nint\r\np\r\n{\r\nget=>1;\r\nset{z=1;}\r\n}=1;\r\n}", "class i9\r\n{\r\n int p\r\n {\r\n get => 1;\r\n set\r\n {\r\n z = 1;\r\n }\r\n } = 1;\r\n}"); TestNormalizeDeclaration("class ia\r\n{\r\nint\r\np\r\n{\r\nget{}\r\nset;\r\n}=1;\r\n}", "class ia\r\n{\r\n int p\r\n {\r\n get\r\n {\r\n }\r\n\r\n set;\r\n } = 1;\r\n}"); TestNormalizeDeclaration("class ib\r\n{\r\nint\r\np\r\n{\r\nget;\r\nset{}\r\n}=1;\r\n}", "class ib\r\n{\r\n int p\r\n {\r\n get;\r\n set\r\n {\r\n }\r\n } = 1;\r\n}"); // indexers TestNormalizeDeclaration("class a{b this[c d]{get;}}", "class a\r\n{\r\n b this[c d] { get; }\r\n}"); TestNormalizeDeclaration("class i1\r\n{\r\nint\r\nthis[b c]\r\n{\r\nget;\r\n}\r\n}", "class i1\r\n{\r\n int this[b c] { get; }\r\n}"); TestNormalizeDeclaration("class i2\r\n{\r\nint\r\nthis[b c]\r\n{\r\nget=>1;\r\n}\r\n}", "class i2\r\n{\r\n int this[b c] { get => 1; }\r\n}"); TestNormalizeDeclaration("class i3\r\n{\r\nint\r\nthis[b c]\r\n{\r\nget{}\r\n}\r\n}", "class i3\r\n{\r\n int this[b c]\r\n {\r\n get\r\n {\r\n }\r\n }\r\n}"); TestNormalizeDeclaration("class i4\r\n{\r\nint\r\nthis[b c]\r\n{\r\nset;\r\n}\r\n}", "class i4\r\n{\r\n int this[b c] { set; }\r\n}"); TestNormalizeDeclaration("class i5\r\n{\r\nint\r\nthis[b c]\r\n{\r\nset{}\r\n}\r\n}", "class i5\r\n{\r\n int this[b c]\r\n {\r\n set\r\n {\r\n }\r\n }\r\n}"); TestNormalizeDeclaration("class i6\r\n{\r\nint\r\nthis[b c]\r\n{\r\ninit;\r\n}\r\n}", "class i6\r\n{\r\n int this[b c] { init; }\r\n}"); TestNormalizeDeclaration("class i7\r\n{\r\nint\r\nthis[b c]\r\n{\r\ninit{}\r\n}\r\n}", "class i7\r\n{\r\n int this[b c]\r\n {\r\n init\r\n {\r\n }\r\n }\r\n}"); TestNormalizeDeclaration("class i8\r\n{\r\nint\r\nthis[b c]\r\n{\r\nget{}\r\nset{}\r\n}\r\n}", "class i8\r\n{\r\n int this[b c]\r\n {\r\n get\r\n {\r\n }\r\n\r\n set\r\n {\r\n }\r\n }\r\n}"); TestNormalizeDeclaration("class i9\r\n{\r\nint\r\nthis[b c]\r\n{\r\nget=>1;\r\nset{z=1;}\r\n}\r\n}", "class i9\r\n{\r\n int this[b c]\r\n {\r\n get => 1;\r\n set\r\n {\r\n z = 1;\r\n }\r\n }\r\n}"); TestNormalizeDeclaration("class ia\r\n{\r\nint\r\nthis[b c]\r\n{\r\nget{}\r\nset;\r\n}\r\n}", "class ia\r\n{\r\n int this[b c]\r\n {\r\n get\r\n {\r\n }\r\n\r\n set;\r\n }\r\n}"); TestNormalizeDeclaration("class ib\r\n{\r\nint\r\nthis[b c]\r\n{\r\nget;\r\nset{}\r\n}\r\n}", "class ib\r\n{\r\n int this[b c]\r\n {\r\n get;\r\n set\r\n {\r\n }\r\n }\r\n}"); // events TestNormalizeDeclaration("class a\r\n{\r\npublic\r\nevent\r\nw\r\ne;\r\n}", "class a\r\n{\r\n public event w e;\r\n}"); TestNormalizeDeclaration("abstract class b\r\n{\r\nevent\r\nw\r\ne\r\n;\r\n}", "abstract class b\r\n{\r\n event w e;\r\n}"); TestNormalizeDeclaration("interface c1\r\n{\r\nevent\r\nw\r\ne\r\n;\r\n}", "interface c1\r\n{\r\n event w e;\r\n}"); TestNormalizeDeclaration("interface c2 : c1\r\n{\r\nabstract\r\nevent\r\nw\r\nc1\r\n.\r\ne\r\n;\r\n}", "interface c2 : c1\r\n{\r\n abstract event w c1.e;\r\n}"); TestNormalizeDeclaration("class d\r\n{\r\nevent w x;\r\nevent\r\nw\r\ne\r\n{\r\nadd\r\n=>\r\nx+=\r\nvalue;\r\nremove\r\n=>x\r\n-=\r\nvalue;\r\n}}", "class d\r\n{\r\n event w x;\r\n event w e { add => x += value; remove => x -= value; }\r\n}"); TestNormalizeDeclaration("class e\r\n{\r\nevent w e\r\n{\r\nadd{}\r\nremove{\r\n}\r\n}\r\n}", "class e\r\n{\r\n event w e\r\n {\r\n add\r\n {\r\n }\r\n\r\n remove\r\n {\r\n }\r\n }\r\n}"); TestNormalizeDeclaration("class f\r\n{\r\nevent w x;\r\nevent w e\r\n{\r\nadd\r\n{\r\nx\r\n+=\r\nvalue;\r\n}\r\nremove\r\n{\r\nx\r\n-=\r\nvalue;\r\n}\r\n}\r\n}", "class f\r\n{\r\n event w x;\r\n event w e\r\n {\r\n add\r\n {\r\n x += value;\r\n }\r\n\r\n remove\r\n {\r\n x -= value;\r\n }\r\n }\r\n}"); TestNormalizeDeclaration("class g\r\n{\r\nextern\r\nevent\r\nw\r\ne\r\n=\r\nnull\r\n;\r\n}", "class g\r\n{\r\n extern event w e = null;\r\n}"); TestNormalizeDeclaration("class h\r\n{\r\npublic event w e\r\n{\r\nadd\r\n=>\r\nc\r\n(\r\n);\r\nremove\r\n=>\r\nd(\r\n);\r\n}\r\n}", "class h\r\n{\r\n public event w e { add => c(); remove => d(); }\r\n}"); TestNormalizeDeclaration("class i\r\n{\r\nevent w e\r\n{\r\nadd;\r\nremove;\r\n}\r\n}", "class i\r\n{\r\n event w e { add; remove; }\r\n}"); // fields TestNormalizeDeclaration("class a{b c;}", "class a\r\n{\r\n b c;\r\n}"); TestNormalizeDeclaration("class a{b c=d;}", "class a\r\n{\r\n b c = d;\r\n}"); TestNormalizeDeclaration("class a{b c=d,e=f;}", "class a\r\n{\r\n b c = d, e = f;\r\n}"); // delegate TestNormalizeDeclaration("delegate a b();", "delegate a b();"); TestNormalizeDeclaration("delegate a b(c);", "delegate a b(c);"); TestNormalizeDeclaration("delegate a b(c,d);", "delegate a b(c, d);"); // enums TestNormalizeDeclaration("enum a{}", "enum a\r\n{\r\n}"); TestNormalizeDeclaration("enum a{b}", "enum a\r\n{\r\n b\r\n}"); TestNormalizeDeclaration("enum a{b,c}", "enum a\r\n{\r\n b,\r\n c\r\n}"); TestNormalizeDeclaration("enum a{b=c}", "enum a\r\n{\r\n b = c\r\n}"); // attributes TestNormalizeDeclaration("[a]class b{}", "[a]\r\nclass b\r\n{\r\n}"); TestNormalizeDeclaration("\t[a]class b{}", "[a]\r\nclass b\r\n{\r\n}"); TestNormalizeDeclaration("[a,b]class c{}", "[a, b]\r\nclass c\r\n{\r\n}"); TestNormalizeDeclaration("[a(b)]class c{}", "[a(b)]\r\nclass c\r\n{\r\n}"); TestNormalizeDeclaration("[a(b,c)]class d{}", "[a(b, c)]\r\nclass d\r\n{\r\n}"); TestNormalizeDeclaration("[a][b]class c{}", "[a]\r\n[b]\r\nclass c\r\n{\r\n}"); TestNormalizeDeclaration("[a:b]class c{}", "[a: b]\r\nclass c\r\n{\r\n}"); // parameter attributes TestNormalizeDeclaration("class c{void M([a]int x,[b] [c,d]int y){}}", "class c\r\n{\r\n void M([a] int x, [b][c, d] int y)\r\n {\r\n }\r\n}"); } [Fact] public void TestFileScopedNamespace() { TestNormalizeDeclaration("namespace NS;class C{}", "namespace NS;\r\nclass C\r\n{\r\n}"); } [Fact] public void TestSpacingOnRecord() { TestNormalizeDeclaration("record class C(int I, int J);", "record class C(int I, int J);"); TestNormalizeDeclaration("record struct S(int I, int J);", "record struct S(int I, int J);"); } [Fact] [WorkItem(23618, "https://github.com/dotnet/roslyn/issues/23618")] public void TestSpacingOnInvocationLikeKeywords() { // no space between typeof and ( TestNormalizeExpression("typeof (T)", "typeof(T)"); // no space between sizeof and ( TestNormalizeExpression("sizeof (T)", "sizeof(T)"); // no space between default and ( TestNormalizeExpression("default (T)", "default(T)"); // no space between new and ( // newline between > and where TestNormalizeDeclaration( "class C<T> where T : new() { }", "class C<T>\r\n where T : new()\r\n{\r\n}"); // no space between this and ( TestNormalizeDeclaration( "class C { C() : this () { } }", "class C\r\n{\r\n C() : this()\r\n {\r\n }\r\n}"); // no space between base and ( TestNormalizeDeclaration( "class C { C() : base () { } }", "class C\r\n{\r\n C() : base()\r\n {\r\n }\r\n}"); // no space between checked and ( TestNormalizeExpression("checked (a)", "checked(a)"); // no space between unchecked and ( TestNormalizeExpression("unchecked (a)", "unchecked(a)"); // no space between __arglist and ( TestNormalizeExpression("__arglist (a)", "__arglist(a)"); } [Fact] [WorkItem(24454, "https://github.com/dotnet/roslyn/issues/24454")] public void TestSpacingOnInterpolatedString() { TestNormalizeExpression("$\"{3:C}\"", "$\"{3:C}\""); TestNormalizeExpression("$\"{3: C}\"", "$\"{3: C}\""); } [Fact] [WorkItem(23618, "https://github.com/dotnet/roslyn/issues/23618")] public void TestSpacingOnMethodConstraint() { // newline between ) and where TestNormalizeDeclaration( "class C { void M<T>() where T : struct { } }", "class C\r\n{\r\n void M<T>()\r\n where T : struct\r\n {\r\n }\r\n}"); } [WorkItem(541684, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541684")] [Fact] public void TestNormalizeRegion1() { // NOTE: the space after the region name is retained, since the text after the space // following "#region" is a single, unstructured trivia element. TestNormalizeDeclaration( "\r\nclass Class \r\n{ \r\n#region Methods \r\nvoid Method() \r\n{ \r\n} \r\n#endregion \r\n}", "class Class\r\n{\r\n#region Methods \r\n void Method()\r\n {\r\n }\r\n#endregion\r\n}"); TestNormalizeDeclaration( "\r\n#region\r\n#endregion", "#region\r\n#endregion\r\n"); TestNormalizeDeclaration( "\r\n#region \r\n#endregion", "#region\r\n#endregion\r\n"); TestNormalizeDeclaration( "\r\n#region name //comment\r\n#endregion", "#region name //comment\r\n#endregion\r\n"); TestNormalizeDeclaration( "\r\n#region /*comment*/\r\n#endregion", "#region /*comment*/\r\n#endregion\r\n"); } [WorkItem(2076, "github")] [Fact] public void TestNormalizeInterpolatedString() { TestNormalizeExpression(@"$""Message is {a}""", @"$""Message is {a}"""); } [WorkItem(528584, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528584")] [Fact] public void TestNormalizeRegion2() { TestNormalizeDeclaration( "\r\n#region //comment\r\n#endregion", // NOTE: the extra newline should be removed, but it's not worth the // effort (see DevDiv #8564) "#region //comment\r\n\r\n#endregion\r\n"); TestNormalizeDeclaration( "\r\n#region //comment\r\n\r\n#endregion", // NOTE: the extra newline should be removed, but it's not worth the // effort (see DevDiv #8564). "#region //comment\r\n\r\n#endregion\r\n"); } private void TestNormalizeDeclaration(string text, string expected) { var node = SyntaxFactory.ParseCompilationUnit(text); Assert.Equal(text.NormalizeLineEndings(), node.ToFullString().NormalizeLineEndings()); var actual = node.NormalizeWhitespace(" ").ToFullString(); Assert.Equal(expected.NormalizeLineEndings(), actual.NormalizeLineEndings()); } [Fact] public void TestNormalizeComments() { TestNormalizeToken("a//b", "a //b\r\n"); TestNormalizeToken("a/*b*/", "a /*b*/"); TestNormalizeToken("//a\r\nb", "//a\r\nb"); TestNormalizeExpression("a/*b*/+c", "a /*b*/ + c"); TestNormalizeExpression("/*a*/b", "/*a*/\r\nb"); TestNormalizeExpression("/*a\r\n*/b", "/*a\r\n*/\r\nb"); TestNormalizeStatement("{/*a*/b}", "{ /*a*/\r\n b\r\n}"); TestNormalizeStatement("{\r\na//b\r\n}", "{\r\n a //b\r\n}"); TestNormalizeStatement("{\r\n//a\r\n}", "{\r\n//a\r\n}"); TestNormalizeStatement("{\r\n//a\r\nb}", "{\r\n //a\r\n b\r\n}"); TestNormalizeStatement("{\r\n/*a*/b}", "{\r\n /*a*/\r\n b\r\n}"); TestNormalizeStatement("{\r\n/// <goo/>\r\na}", "{\r\n /// <goo/>\r\n a\r\n}"); TestNormalizeStatement("{\r\n///<goo/>\r\na}", "{\r\n ///<goo/>\r\n a\r\n}"); TestNormalizeStatement("{\r\n/// <goo>\r\n/// </goo>\r\na}", "{\r\n /// <goo>\r\n /// </goo>\r\n a\r\n}"); TestNormalizeToken("/// <goo>\r\n/// </goo>\r\na", "/// <goo>\r\n/// </goo>\r\na"); TestNormalizeStatement("{\r\n/*** <goo/> ***/\r\na}", "{\r\n /*** <goo/> ***/\r\n a\r\n}"); TestNormalizeStatement("{\r\n/*** <goo/>\r\n ***/\r\na}", "{\r\n /*** <goo/>\r\n ***/\r\n a\r\n}"); } private void TestNormalizeToken(string text, string expected) { var token = SyntaxFactory.ParseToken(text); var actual = token.NormalizeWhitespace().ToFullString(); Assert.Equal(expected, actual); } [Fact] [WorkItem(1066, "github")] public void TestNormalizePreprocessorDirectives() { // directive as node TestNormalize(SyntaxFactory.DefineDirectiveTrivia(SyntaxFactory.Identifier("a"), false), "#define a\r\n"); // directive as trivia TestNormalizeTrivia(" # define a", "#define a\r\n"); TestNormalizeTrivia("#if(a||b)", "#if (a || b)\r\n"); TestNormalizeTrivia("#if(a&&b)", "#if (a && b)\r\n"); TestNormalizeTrivia(" #if a\r\n #endif", "#if a\r\n#endif\r\n"); TestNormalize( SyntaxFactory.TriviaList( SyntaxFactory.Trivia( SyntaxFactory.IfDirectiveTrivia(SyntaxFactory.IdentifierName("a"), false, false, false)), SyntaxFactory.Trivia( SyntaxFactory.EndIfDirectiveTrivia(false))), "#if a\r\n#endif\r\n"); TestNormalizeTrivia("#endregion goo", "#endregion goo\r\n"); TestNormalizeDeclaration( @"#pragma warning disable 123 namespace goo { } #pragma warning restore 123", @"#pragma warning disable 123 namespace goo { } #pragma warning restore 123 "); } [Fact] [WorkItem(531607, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531607")] public void TestNormalizeLineDirectiveTrivia() { TestNormalize( SyntaxFactory.TriviaList( SyntaxFactory.Trivia( SyntaxFactory.LineDirectiveTrivia( SyntaxFactory.Literal(1), true) .WithEndOfDirectiveToken( SyntaxFactory.Token( SyntaxFactory.TriviaList( SyntaxFactory.Trivia( SyntaxFactory.SkippedTokensTrivia() .WithTokens( SyntaxFactory.TokenList( SyntaxFactory.Literal(@"""a\b"""))))), SyntaxKind.EndOfDirectiveToken, default(SyntaxTriviaList))))), @"#line 1 ""\""a\\b\"""" "); // Note: without all the escaping, it looks like this '#line 1 @"""a\b"""' (i.e. the string literal has a value of '"a\b"'). // Note: the literal was formatted as a C# string literal, not as a directive string literal. } [WorkItem(538115, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538115")] [Fact] public void TestNormalizeWithinDirectives() { TestNormalizeDeclaration( "class C\r\n{\r\n#if true\r\nvoid Goo(A x) { }\r\n#else\r\n#endif\r\n}\r\n", "class C\r\n{\r\n#if true\r\n void Goo(A x)\r\n {\r\n }\r\n#else\r\n#endif\r\n}"); } [WorkItem(542887, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542887")] [Fact] public void TestFormattingForBlockSyntax() { var code = @"class c1 { void goo() { { int i = 1; } } }"; var tree = SyntaxFactory.ParseSyntaxTree(code); TestNormalize(tree.GetCompilationUnitRoot(), @"class c1 { void goo() { { int i = 1; } } }".NormalizeLineEndings()); } [WorkItem(1079042, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1079042")] [Fact] public void TestNormalizeDocumentationComments() { var code = @"class c1 { ///<summary> /// A documentation comment ///</summary> void goo() { } }"; var tree = SyntaxFactory.ParseSyntaxTree(code); TestNormalize(tree.GetCompilationUnitRoot(), "class c1\r\n" + "{\r\n" + // The normalizer doesn't change line endings in comments, // see https://github.com/dotnet/roslyn/issues/8536 $" ///<summary>{Environment.NewLine}" + $" /// A documentation comment{Environment.NewLine}" + $" ///</summary>{Environment.NewLine}" + " void goo()\r\n" + " {\r\n" + " }\r\n" + "}"); } [Fact] public void TestNormalizeDocumentationComments2() { var code = @"class c1 { /// <summary> /// A documentation comment /// </summary> void goo() { } }"; var tree = SyntaxFactory.ParseSyntaxTree(code); TestNormalize(tree.GetCompilationUnitRoot(), "class c1\r\n" + "{\r\n" + // The normalizer doesn't change line endings in comments, // see https://github.com/dotnet/roslyn/issues/8536 $" /// <summary>{Environment.NewLine}" + $" /// A documentation comment{Environment.NewLine}" + $" /// </summary>{Environment.NewLine}" + " void goo()\r\n" + " {\r\n" + " }\r\n" + "}"); } [Fact] public void TestNormalizeEOL() { var code = "class c{}"; var expected = "class c\n{\n}"; var actual = SyntaxFactory.ParseCompilationUnit(code).NormalizeWhitespace(indentation: " ", eol: "\n").ToFullString(); Assert.Equal(expected, actual); } [Fact] public void TestNormalizeTabs() { var code = "class c{void m(){}}"; var expected = "class c\r\n{\r\n\tvoid m()\r\n\t{\r\n\t}\r\n}"; var actual = SyntaxFactory.ParseCompilationUnit(code).NormalizeWhitespace(indentation: "\t").ToFullString(); Assert.Equal(expected, actual); } [Fact] [WorkItem(29390, "https://github.com/dotnet/roslyn/issues/29390")] public void TestNormalizeTuples() { TestNormalizeDeclaration("new(string prefix,string uri)[10]", "new (string prefix, string uri)[10]"); TestNormalizeDeclaration("(string prefix,string uri)[]ns", "(string prefix, string uri)[] ns"); TestNormalizeDeclaration("(string prefix,(string uri,string help))ns", "(string prefix, (string uri, string help)) ns"); TestNormalizeDeclaration("(string prefix,string uri)ns", "(string prefix, string uri) ns"); TestNormalizeDeclaration("public void Foo((string prefix,string uri)ns)", "public void Foo((string prefix, string uri) ns)"); TestNormalizeDeclaration("public (string prefix,string uri)Foo()", "public (string prefix, string uri) Foo()"); } [Fact] [WorkItem(50664, "https://github.com/dotnet/roslyn/issues/50664")] public void TestNormalizeFunctionPointer() { var content = @"unsafe class C { delegate * < int , int > functionPointer; }"; var expected = @"unsafe class C { delegate*<int, int> functionPointer; }"; TestNormalizeDeclaration(content, expected); } [Fact] [WorkItem(50664, "https://github.com/dotnet/roslyn/issues/50664")] public void TestNormalizeFunctionPointerWithManagedCallingConvention() { var content = @"unsafe class C { delegate *managed < int , int > functionPointer; }"; var expected = @"unsafe class C { delegate* managed<int, int> functionPointer; }"; TestNormalizeDeclaration(content, expected); } [Fact] [WorkItem(50664, "https://github.com/dotnet/roslyn/issues/50664")] public void TestNormalizeFunctionPointerWithUnmanagedCallingConvention() { var content = @"unsafe class C { delegate *unmanaged < int , int > functionPointer; }"; var expected = @"unsafe class C { delegate* unmanaged<int, int> functionPointer; }"; TestNormalizeDeclaration(content, expected); } [Fact] [WorkItem(50664, "https://github.com/dotnet/roslyn/issues/50664")] public void TestNormalizeFunctionPointerWithUnmanagedCallingConventionAndSpecifiers() { var content = @"unsafe class C { delegate *unmanaged [ Cdecl , Thiscall ] < int , int > functionPointer; }"; var expected = @"unsafe class C { delegate* unmanaged[Cdecl, Thiscall]<int, int> functionPointer; }"; TestNormalizeDeclaration(content, expected); } [Fact] [WorkItem(53254, "https://github.com/dotnet/roslyn/issues/53254")] public void TestNormalizeColonInConstructorInitializer() { var content = @"class Base { } class Derived : Base { public Derived():base(){} }"; var expected = @"class Base { } class Derived : Base { public Derived() : base() { } }"; TestNormalizeDeclaration(content, expected); } [Fact] [WorkItem(49732, "https://github.com/dotnet/roslyn/issues/49732")] public void TestNormalizeXmlInDocComment() { var code = @"/// <returns> /// If this method succeeds, it returns <b xmlns:loc=""http://microsoft.com/wdcml/l10n"">S_OK</b>. /// </returns>"; TestNormalizeDeclaration(code, code); } [Theory] [InlineData("_=()=>{};", "_ = () =>\r\n{\r\n};")] [InlineData("_=x=>{};", "_ = x =>\r\n{\r\n};")] [InlineData("Add(()=>{});", "Add(() =>\r\n{\r\n});")] [InlineData("Add(delegate(){});", "Add(delegate ()\r\n{\r\n});")] [InlineData("Add(()=>{{_=x=>{};}});", "Add(() =>\r\n{\r\n {\r\n _ = x =>\r\n {\r\n };\r\n }\r\n});")] [WorkItem(46656, "https://github.com/dotnet/roslyn/issues/46656")] public void TestNormalizeBlockAnonymousFunctions(string actual, string expected) { TestNormalizeStatement(actual, expected); } [Fact] public void TestNormalizeExtendedPropertyPattern() { var text = "_ = this is{Property . Property :2};"; var expected = @"_ = this is { Property.Property: 2 };"; TestNormalizeStatement(text, expected); } private void TestNormalize(CSharpSyntaxNode node, string expected) { var actual = node.NormalizeWhitespace(" ").ToFullString(); Assert.Equal(expected, actual); } private void TestNormalizeTrivia(string text, string expected) { var list = SyntaxFactory.ParseLeadingTrivia(text); TestNormalize(list, expected); } private void TestNormalize(SyntaxTriviaList trivia, string expected) { var actual = trivia.NormalizeWhitespace(" ").ToFullString().NormalizeLineEndings(); Assert.Equal(expected.NormalizeLineEndings(), actual); } } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/EditorFeatures/Core/EditorConfigSettings/Aggregator/SettingsAggregatorFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.Editor.EditorConfigSettings { [ExportWorkspaceServiceFactory(typeof(ISettingsAggregator), ServiceLayer.Default), Shared] internal class SettingsAggregatorFactory : IWorkspaceServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public SettingsAggregatorFactory() { } public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) => new SettingsAggregator(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. using System; using System.Composition; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.Editor.EditorConfigSettings { [ExportWorkspaceServiceFactory(typeof(ISettingsAggregator), ServiceLayer.Default), Shared] internal class SettingsAggregatorFactory : IWorkspaceServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public SettingsAggregatorFactory() { } public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) => new SettingsAggregator(workspaceServices.Workspace); } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/EditorFeatures/Test/Utilities/AsyncLazyTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { public class AsyncLazyTests { [Fact, Trait(Traits.Feature, Traits.Features.AsyncLazy)] public void CancellationDuringInlinedComputationFromGetValueStillCachesResult() { CancellationDuringInlinedComputationFromGetValueOrGetValueAsyncStillCachesResultCore((lazy, ct) => lazy.GetValue(ct), includeSynchronousComputation: true); CancellationDuringInlinedComputationFromGetValueOrGetValueAsyncStillCachesResultCore((lazy, ct) => lazy.GetValue(ct), includeSynchronousComputation: false); } private static void CancellationDuringInlinedComputationFromGetValueOrGetValueAsyncStillCachesResultCore(Func<AsyncLazy<object>, CancellationToken, object> doGetValue, bool includeSynchronousComputation) { var computations = 0; var requestCancellationTokenSource = new CancellationTokenSource(); object createdObject = null; Func<CancellationToken, object> synchronousComputation = c => { Interlocked.Increment(ref computations); // We do not want to ever use the cancellation token that we are passed to this // computation. Rather, we will ignore it but cancel any request that is // outstanding. requestCancellationTokenSource.Cancel(); createdObject = new object(); return createdObject; }; var lazy = new AsyncLazy<object>( c => Task.FromResult(synchronousComputation(c)), includeSynchronousComputation ? synchronousComputation : null, cacheResult: true); var thrownException = Assert.Throws<OperationCanceledException>(() => { // Do a first request. Even though we will get a cancellation during the evaluation, // since we handed a result back, that result must be cached. doGetValue(lazy, requestCancellationTokenSource.Token); }); // And a second request. We'll let this one complete normally. var secondRequestResult = doGetValue(lazy, CancellationToken.None); // We should have gotten the same cached result, and we should have only computed once. Assert.Same(createdObject, secondRequestResult); Assert.Equal(1, computations); } [Fact, Trait(Traits.Feature, Traits.Features.AsyncLazy)] public void SynchronousRequestShouldCacheValueWithAsynchronousComputeFunction() { var lazy = new AsyncLazy<object>(c => Task.FromResult(new object()), cacheResult: true); var firstRequestResult = lazy.GetValue(CancellationToken.None); var secondRequestResult = lazy.GetValue(CancellationToken.None); Assert.Same(secondRequestResult, firstRequestResult); } [Theory] [CombinatorialData] public async Task AwaitingProducesCorrectException(bool producerAsync, bool consumerAsync) { var exception = new ArgumentException(); Func<CancellationToken, Task<object>> asynchronousComputeFunction = async cancellationToken => { await Task.Yield(); throw exception; }; Func<CancellationToken, object> synchronousComputeFunction = cancellationToken => { throw exception; }; var lazy = producerAsync ? new AsyncLazy<object>(asynchronousComputeFunction, cacheResult: true) : new AsyncLazy<object>(asynchronousComputeFunction, synchronousComputeFunction, cacheResult: true); var actual = consumerAsync ? await Assert.ThrowsAsync<ArgumentException>(async () => await lazy.GetValueAsync(CancellationToken.None)) : Assert.Throws<ArgumentException>(() => lazy.GetValue(CancellationToken.None)); Assert.Same(exception, actual); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { public class AsyncLazyTests { [Fact, Trait(Traits.Feature, Traits.Features.AsyncLazy)] public void CancellationDuringInlinedComputationFromGetValueStillCachesResult() { CancellationDuringInlinedComputationFromGetValueOrGetValueAsyncStillCachesResultCore((lazy, ct) => lazy.GetValue(ct), includeSynchronousComputation: true); CancellationDuringInlinedComputationFromGetValueOrGetValueAsyncStillCachesResultCore((lazy, ct) => lazy.GetValue(ct), includeSynchronousComputation: false); } private static void CancellationDuringInlinedComputationFromGetValueOrGetValueAsyncStillCachesResultCore(Func<AsyncLazy<object>, CancellationToken, object> doGetValue, bool includeSynchronousComputation) { var computations = 0; var requestCancellationTokenSource = new CancellationTokenSource(); object createdObject = null; Func<CancellationToken, object> synchronousComputation = c => { Interlocked.Increment(ref computations); // We do not want to ever use the cancellation token that we are passed to this // computation. Rather, we will ignore it but cancel any request that is // outstanding. requestCancellationTokenSource.Cancel(); createdObject = new object(); return createdObject; }; var lazy = new AsyncLazy<object>( c => Task.FromResult(synchronousComputation(c)), includeSynchronousComputation ? synchronousComputation : null, cacheResult: true); var thrownException = Assert.Throws<OperationCanceledException>(() => { // Do a first request. Even though we will get a cancellation during the evaluation, // since we handed a result back, that result must be cached. doGetValue(lazy, requestCancellationTokenSource.Token); }); // And a second request. We'll let this one complete normally. var secondRequestResult = doGetValue(lazy, CancellationToken.None); // We should have gotten the same cached result, and we should have only computed once. Assert.Same(createdObject, secondRequestResult); Assert.Equal(1, computations); } [Fact, Trait(Traits.Feature, Traits.Features.AsyncLazy)] public void SynchronousRequestShouldCacheValueWithAsynchronousComputeFunction() { var lazy = new AsyncLazy<object>(c => Task.FromResult(new object()), cacheResult: true); var firstRequestResult = lazy.GetValue(CancellationToken.None); var secondRequestResult = lazy.GetValue(CancellationToken.None); Assert.Same(secondRequestResult, firstRequestResult); } [Theory] [CombinatorialData] public async Task AwaitingProducesCorrectException(bool producerAsync, bool consumerAsync) { var exception = new ArgumentException(); Func<CancellationToken, Task<object>> asynchronousComputeFunction = async cancellationToken => { await Task.Yield(); throw exception; }; Func<CancellationToken, object> synchronousComputeFunction = cancellationToken => { throw exception; }; var lazy = producerAsync ? new AsyncLazy<object>(asynchronousComputeFunction, cacheResult: true) : new AsyncLazy<object>(asynchronousComputeFunction, synchronousComputeFunction, cacheResult: true); var actual = consumerAsync ? await Assert.ThrowsAsync<ArgumentException>(async () => await lazy.GetValueAsync(CancellationToken.None)) : Assert.Throws<ArgumentException>(() => lazy.GetValue(CancellationToken.None)); Assert.Same(exception, actual); } } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/EditorFeatures/Core/Implementation/Diagnostics/AbstractDiagnosticsTaggerProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Shared.Preview; using Microsoft.CodeAnalysis.Editor.Shared.Tagging; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editor.Tagging; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Tagging; namespace Microsoft.CodeAnalysis.Editor.Implementation.Diagnostics { /// <summary> /// Diagnostics works slightly differently than the rest of the taggers. For diagnostics, /// we want to try to have an individual tagger per diagnostic producer per buffer. /// However, the editor only allows a single tagger provider per buffer. So in order to /// get the abstraction we want, we create one outer tagger provider that is associated /// with the buffer. Then, under the covers, we create individual async taggers for each /// diagnostic producer we hear about for that buffer. /// /// In essence, we have one tagger that wraps a multitude of taggers it delegates to. /// Each of these taggers is nicely asynchronous and properly works within the async /// tagging infrastructure. /// </summary> internal abstract partial class AbstractDiagnosticsTaggerProvider<TTag> : AsynchronousTaggerProvider<TTag> where TTag : ITag { private readonly IDiagnosticService _diagnosticService; /// <summary> /// Keep track of the ITextSnapshot for the open Document that was used when diagnostics were /// produced for it. We need that because the DiagnoticService does not keep track of this /// snapshot (so as to not hold onto a lot of memory), which means when we query it for /// diagnostics, we don't know how to map the span of the diagnostic to the current snapshot /// we're tagging. /// </summary> private static readonly ConditionalWeakTable<object, ITextSnapshot> _diagnosticIdToTextSnapshot = new(); protected AbstractDiagnosticsTaggerProvider( IThreadingContext threadingContext, IDiagnosticService diagnosticService, IAsynchronousOperationListener listener) : base(threadingContext, listener) { _diagnosticService = diagnosticService; _diagnosticService.DiagnosticsUpdated += OnDiagnosticsUpdated; } private void OnDiagnosticsUpdated(object? sender, DiagnosticsUpdatedArgs e) { if (e.Solution == null || e.DocumentId == null) { return; } if (_diagnosticIdToTextSnapshot.TryGetValue(e.Id, out var snapshot)) { return; } var document = e.Solution.GetDocument(e.DocumentId); // Open documents *should* always have their SourceText available, but we cannot guarantee // (i.e. assert) that they do. That's because we're not on the UI thread here, so there's // a small risk that between calling .IsOpen the file may then close, which then would // cause TryGetText to fail. However, that's ok. In that case, if we do need to tag this // document, we'll just use the current editor snapshot. If that's the same, then the tags // will be hte same. If it is different, we'll eventually hear about the new diagnostics // for it and we'll reach our fixed point. if (document != null && document.IsOpen()) { // This should always be fast since the document is open. var sourceText = document.State.GetTextSynchronously(cancellationToken: default); snapshot = sourceText.FindCorrespondingEditorTextSnapshot(); if (snapshot != null) { _diagnosticIdToTextSnapshot.GetValue(e.Id, _ => snapshot); } } } protected override TaggerDelay EventChangeDelay => TaggerDelay.Short; protected override TaggerDelay AddedTagNotificationDelay => TaggerDelay.OnIdle; protected override ITaggerEventSource CreateEventSource(ITextView textViewOpt, ITextBuffer subjectBuffer) { return TaggerEventSources.Compose( TaggerEventSources.OnDocumentActiveContextChanged(subjectBuffer), TaggerEventSources.OnWorkspaceRegistrationChanged(subjectBuffer), TaggerEventSources.OnDiagnosticsChanged(subjectBuffer, _diagnosticService)); } protected internal abstract bool IsEnabled { get; } protected internal abstract bool IncludeDiagnostic(DiagnosticData data); protected internal abstract ITagSpan<TTag>? CreateTagSpan(Workspace workspace, bool isLiveUpdate, SnapshotSpan span, DiagnosticData data); /// <summary> /// Get the <see cref="DiagnosticDataLocation"/> that should have the tag applied to it. /// In most cases, this is the <see cref="DiagnosticData.DataLocation"/> but overrides can change it (e.g. unnecessary classifications). /// </summary> /// <param name="diagnosticData">the diagnostic containing the location(s).</param> /// <returns>an array of locations that should have the tag applied.</returns> protected internal virtual ImmutableArray<DiagnosticDataLocation> GetLocationsToTag(DiagnosticData diagnosticData) => diagnosticData.DataLocation is object ? ImmutableArray.Create(diagnosticData.DataLocation) : ImmutableArray<DiagnosticDataLocation>.Empty; protected override Task ProduceTagsAsync(TaggerContext<TTag> context, DocumentSnapshotSpan spanToTag, int? caretPosition) { return ProduceTagsAsync(context, spanToTag); } private async Task ProduceTagsAsync(TaggerContext<TTag> context, DocumentSnapshotSpan spanToTag) { if (!this.IsEnabled) { return; } var document = spanToTag.Document; if (document == null) { return; } var editorSnapshot = spanToTag.SnapshotSpan.Snapshot; var cancellationToken = context.CancellationToken; var workspace = document.Project.Solution.Workspace; // See if we've marked any spans as those we want to suppress diagnostics for. // This can happen for buffers used in the preview workspace where some feature // is generating code that it doesn't want errors shown for. var buffer = editorSnapshot.TextBuffer; var suppressedDiagnosticsSpans = (NormalizedSnapshotSpanCollection?)null; buffer?.Properties.TryGetProperty(PredefinedPreviewTaggerKeys.SuppressDiagnosticsSpansKey, out suppressedDiagnosticsSpans); var buckets = _diagnosticService.GetPushDiagnosticBuckets( workspace, document.Project.Id, document.Id, InternalDiagnosticsOptions.NormalDiagnosticMode, context.CancellationToken); foreach (var bucket in buckets) { await ProduceTagsAsync( context, spanToTag, workspace, document, suppressedDiagnosticsSpans, bucket, cancellationToken).ConfigureAwait(false); } } private async Task ProduceTagsAsync( TaggerContext<TTag> context, DocumentSnapshotSpan spanToTag, Workspace workspace, Document document, NormalizedSnapshotSpanCollection? suppressedDiagnosticsSpans, DiagnosticBucket bucket, CancellationToken cancellationToken) { try { var id = bucket.Id; var diagnostics = await _diagnosticService.GetPushDiagnosticsAsync( workspace, document.Project.Id, document.Id, id, includeSuppressedDiagnostics: false, diagnosticMode: InternalDiagnosticsOptions.NormalDiagnosticMode, cancellationToken).ConfigureAwait(false); var isLiveUpdate = id is ISupportLiveUpdate; var requestedSpan = spanToTag.SnapshotSpan; var editorSnapshot = requestedSpan.Snapshot; // Try to get the text snapshot that these diagnostics were created against. // This may fail if this tagger was created *after* the notification for the // diagnostics was already issued. That's ok. We'll take the spans as reported // and apply them directly to the snapshot we have. Either no new changes will // have happened, and these spans will be accurate, or a change will happen // and we'll hear about and it update the spans shortly to the right position. // // Also, only use the diagnoticSnapshot if its text buffer matches our. The text // buffer might be different if the file was closed/reopened. // Note: when this happens, the diagnostic service will reanalyze the file. So // up to date diagnostic spans will appear shortly after this. _diagnosticIdToTextSnapshot.TryGetValue(id, out var diagnosticSnapshot); diagnosticSnapshot = diagnosticSnapshot?.TextBuffer == editorSnapshot.TextBuffer ? diagnosticSnapshot : editorSnapshot; var sourceText = diagnosticSnapshot.AsText(); foreach (var diagnosticData in diagnostics) { if (this.IncludeDiagnostic(diagnosticData)) { // We're going to be retrieving the diagnostics against the last time the engine // computed them against this document *id*. That might have been a different // version of the document vs what we're looking at now. But that's ok: // // 1) GetExistingOrCalculatedTextSpan will ensure that the diagnostics spans are // contained within 'editorSnapshot'. // 2) We'll eventually hear about an update to the diagnostics for this document // for whatever edits happened between the last time and this current snapshot. // So we'll eventually reach a point where the diagnostics exactly match the // editorSnapshot. var diagnosticSpans = this.GetLocationsToTag(diagnosticData) .Select(location => GetDiagnosticSnapshotSpan(location, diagnosticSnapshot, editorSnapshot, sourceText)); foreach (var diagnosticSpan in diagnosticSpans) { if (diagnosticSpan.IntersectsWith(requestedSpan) && !IsSuppressed(suppressedDiagnosticsSpans, diagnosticSpan)) { var tagSpan = this.CreateTagSpan(workspace, isLiveUpdate, diagnosticSpan, diagnosticData); if (tagSpan != null) { context.AddTag(tagSpan); } } } } } } catch (ArgumentOutOfRangeException ex) when (FatalError.ReportAndCatch(ex)) { // https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=428328&_a=edit&triage=false // explicitly report NFW to find out what is causing us for out of range. // stop crashing on such occations return; } static SnapshotSpan GetDiagnosticSnapshotSpan(DiagnosticDataLocation diagnosticDataLocation, ITextSnapshot diagnosticSnapshot, ITextSnapshot editorSnapshot, SourceText sourceText) { return DiagnosticData.GetExistingOrCalculatedTextSpan(diagnosticDataLocation, sourceText) .ToSnapshotSpan(diagnosticSnapshot) .TranslateTo(editorSnapshot, SpanTrackingMode.EdgeExclusive); } } private static bool IsSuppressed(NormalizedSnapshotSpanCollection? suppressedSpans, SnapshotSpan span) => suppressedSpans != null && suppressedSpans.IntersectsWith(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. using System; using System.Collections.Immutable; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Shared.Preview; using Microsoft.CodeAnalysis.Editor.Shared.Tagging; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editor.Tagging; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Tagging; namespace Microsoft.CodeAnalysis.Editor.Implementation.Diagnostics { /// <summary> /// Diagnostics works slightly differently than the rest of the taggers. For diagnostics, /// we want to try to have an individual tagger per diagnostic producer per buffer. /// However, the editor only allows a single tagger provider per buffer. So in order to /// get the abstraction we want, we create one outer tagger provider that is associated /// with the buffer. Then, under the covers, we create individual async taggers for each /// diagnostic producer we hear about for that buffer. /// /// In essence, we have one tagger that wraps a multitude of taggers it delegates to. /// Each of these taggers is nicely asynchronous and properly works within the async /// tagging infrastructure. /// </summary> internal abstract partial class AbstractDiagnosticsTaggerProvider<TTag> : AsynchronousTaggerProvider<TTag> where TTag : ITag { private readonly IDiagnosticService _diagnosticService; /// <summary> /// Keep track of the ITextSnapshot for the open Document that was used when diagnostics were /// produced for it. We need that because the DiagnoticService does not keep track of this /// snapshot (so as to not hold onto a lot of memory), which means when we query it for /// diagnostics, we don't know how to map the span of the diagnostic to the current snapshot /// we're tagging. /// </summary> private static readonly ConditionalWeakTable<object, ITextSnapshot> _diagnosticIdToTextSnapshot = new(); protected AbstractDiagnosticsTaggerProvider( IThreadingContext threadingContext, IDiagnosticService diagnosticService, IAsynchronousOperationListener listener) : base(threadingContext, listener) { _diagnosticService = diagnosticService; _diagnosticService.DiagnosticsUpdated += OnDiagnosticsUpdated; } private void OnDiagnosticsUpdated(object? sender, DiagnosticsUpdatedArgs e) { if (e.Solution == null || e.DocumentId == null) { return; } if (_diagnosticIdToTextSnapshot.TryGetValue(e.Id, out var snapshot)) { return; } var document = e.Solution.GetDocument(e.DocumentId); // Open documents *should* always have their SourceText available, but we cannot guarantee // (i.e. assert) that they do. That's because we're not on the UI thread here, so there's // a small risk that between calling .IsOpen the file may then close, which then would // cause TryGetText to fail. However, that's ok. In that case, if we do need to tag this // document, we'll just use the current editor snapshot. If that's the same, then the tags // will be hte same. If it is different, we'll eventually hear about the new diagnostics // for it and we'll reach our fixed point. if (document != null && document.IsOpen()) { // This should always be fast since the document is open. var sourceText = document.State.GetTextSynchronously(cancellationToken: default); snapshot = sourceText.FindCorrespondingEditorTextSnapshot(); if (snapshot != null) { _diagnosticIdToTextSnapshot.GetValue(e.Id, _ => snapshot); } } } protected override TaggerDelay EventChangeDelay => TaggerDelay.Short; protected override TaggerDelay AddedTagNotificationDelay => TaggerDelay.OnIdle; protected override ITaggerEventSource CreateEventSource(ITextView textViewOpt, ITextBuffer subjectBuffer) { return TaggerEventSources.Compose( TaggerEventSources.OnDocumentActiveContextChanged(subjectBuffer), TaggerEventSources.OnWorkspaceRegistrationChanged(subjectBuffer), TaggerEventSources.OnDiagnosticsChanged(subjectBuffer, _diagnosticService)); } protected internal abstract bool IsEnabled { get; } protected internal abstract bool IncludeDiagnostic(DiagnosticData data); protected internal abstract ITagSpan<TTag>? CreateTagSpan(Workspace workspace, bool isLiveUpdate, SnapshotSpan span, DiagnosticData data); /// <summary> /// Get the <see cref="DiagnosticDataLocation"/> that should have the tag applied to it. /// In most cases, this is the <see cref="DiagnosticData.DataLocation"/> but overrides can change it (e.g. unnecessary classifications). /// </summary> /// <param name="diagnosticData">the diagnostic containing the location(s).</param> /// <returns>an array of locations that should have the tag applied.</returns> protected internal virtual ImmutableArray<DiagnosticDataLocation> GetLocationsToTag(DiagnosticData diagnosticData) => diagnosticData.DataLocation is object ? ImmutableArray.Create(diagnosticData.DataLocation) : ImmutableArray<DiagnosticDataLocation>.Empty; protected override Task ProduceTagsAsync(TaggerContext<TTag> context, DocumentSnapshotSpan spanToTag, int? caretPosition) { return ProduceTagsAsync(context, spanToTag); } private async Task ProduceTagsAsync(TaggerContext<TTag> context, DocumentSnapshotSpan spanToTag) { if (!this.IsEnabled) { return; } var document = spanToTag.Document; if (document == null) { return; } var editorSnapshot = spanToTag.SnapshotSpan.Snapshot; var cancellationToken = context.CancellationToken; var workspace = document.Project.Solution.Workspace; // See if we've marked any spans as those we want to suppress diagnostics for. // This can happen for buffers used in the preview workspace where some feature // is generating code that it doesn't want errors shown for. var buffer = editorSnapshot.TextBuffer; var suppressedDiagnosticsSpans = (NormalizedSnapshotSpanCollection?)null; buffer?.Properties.TryGetProperty(PredefinedPreviewTaggerKeys.SuppressDiagnosticsSpansKey, out suppressedDiagnosticsSpans); var buckets = _diagnosticService.GetPushDiagnosticBuckets( workspace, document.Project.Id, document.Id, InternalDiagnosticsOptions.NormalDiagnosticMode, context.CancellationToken); foreach (var bucket in buckets) { await ProduceTagsAsync( context, spanToTag, workspace, document, suppressedDiagnosticsSpans, bucket, cancellationToken).ConfigureAwait(false); } } private async Task ProduceTagsAsync( TaggerContext<TTag> context, DocumentSnapshotSpan spanToTag, Workspace workspace, Document document, NormalizedSnapshotSpanCollection? suppressedDiagnosticsSpans, DiagnosticBucket bucket, CancellationToken cancellationToken) { try { var id = bucket.Id; var diagnostics = await _diagnosticService.GetPushDiagnosticsAsync( workspace, document.Project.Id, document.Id, id, includeSuppressedDiagnostics: false, diagnosticMode: InternalDiagnosticsOptions.NormalDiagnosticMode, cancellationToken).ConfigureAwait(false); var isLiveUpdate = id is ISupportLiveUpdate; var requestedSpan = spanToTag.SnapshotSpan; var editorSnapshot = requestedSpan.Snapshot; // Try to get the text snapshot that these diagnostics were created against. // This may fail if this tagger was created *after* the notification for the // diagnostics was already issued. That's ok. We'll take the spans as reported // and apply them directly to the snapshot we have. Either no new changes will // have happened, and these spans will be accurate, or a change will happen // and we'll hear about and it update the spans shortly to the right position. // // Also, only use the diagnoticSnapshot if its text buffer matches our. The text // buffer might be different if the file was closed/reopened. // Note: when this happens, the diagnostic service will reanalyze the file. So // up to date diagnostic spans will appear shortly after this. _diagnosticIdToTextSnapshot.TryGetValue(id, out var diagnosticSnapshot); diagnosticSnapshot = diagnosticSnapshot?.TextBuffer == editorSnapshot.TextBuffer ? diagnosticSnapshot : editorSnapshot; var sourceText = diagnosticSnapshot.AsText(); foreach (var diagnosticData in diagnostics) { if (this.IncludeDiagnostic(diagnosticData)) { // We're going to be retrieving the diagnostics against the last time the engine // computed them against this document *id*. That might have been a different // version of the document vs what we're looking at now. But that's ok: // // 1) GetExistingOrCalculatedTextSpan will ensure that the diagnostics spans are // contained within 'editorSnapshot'. // 2) We'll eventually hear about an update to the diagnostics for this document // for whatever edits happened between the last time and this current snapshot. // So we'll eventually reach a point where the diagnostics exactly match the // editorSnapshot. var diagnosticSpans = this.GetLocationsToTag(diagnosticData) .Select(location => GetDiagnosticSnapshotSpan(location, diagnosticSnapshot, editorSnapshot, sourceText)); foreach (var diagnosticSpan in diagnosticSpans) { if (diagnosticSpan.IntersectsWith(requestedSpan) && !IsSuppressed(suppressedDiagnosticsSpans, diagnosticSpan)) { var tagSpan = this.CreateTagSpan(workspace, isLiveUpdate, diagnosticSpan, diagnosticData); if (tagSpan != null) { context.AddTag(tagSpan); } } } } } } catch (ArgumentOutOfRangeException ex) when (FatalError.ReportAndCatch(ex)) { // https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=428328&_a=edit&triage=false // explicitly report NFW to find out what is causing us for out of range. // stop crashing on such occations return; } static SnapshotSpan GetDiagnosticSnapshotSpan(DiagnosticDataLocation diagnosticDataLocation, ITextSnapshot diagnosticSnapshot, ITextSnapshot editorSnapshot, SourceText sourceText) { return DiagnosticData.GetExistingOrCalculatedTextSpan(diagnosticDataLocation, sourceText) .ToSnapshotSpan(diagnosticSnapshot) .TranslateTo(editorSnapshot, SpanTrackingMode.EdgeExclusive); } } private static bool IsSuppressed(NormalizedSnapshotSpanCollection? suppressedSpans, SnapshotSpan span) => suppressedSpans != null && suppressedSpans.IntersectsWith(span); } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/VisualStudio/Core/Def/Implementation/TaskList/ProjectExternalErrorReporter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.Extensions; using Microsoft.VisualStudio.LanguageServices.Implementation.Venus; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.TextManager.Interop; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.TaskList { internal sealed class ProjectExternalErrorReporter : IVsReportExternalErrors, IVsLanguageServiceBuildErrorReporter2 { internal static readonly ImmutableArray<string> CustomTags = ImmutableArray.Create(WellKnownDiagnosticTags.Telemetry); internal static readonly ImmutableArray<string> CompilerDiagnosticCustomTags = ImmutableArray.Create(WellKnownDiagnosticTags.Compiler, WellKnownDiagnosticTags.Telemetry); private readonly ProjectId _projectId; private readonly string _errorCodePrefix; private readonly string _language; private readonly VisualStudioWorkspaceImpl _workspace; [Obsolete("This is a compatibility shim for F#; please do not use it.")] public ProjectExternalErrorReporter(ProjectId projectId, string errorCodePrefix, IServiceProvider serviceProvider) : this(projectId, errorCodePrefix, LanguageNames.FSharp, (VisualStudioWorkspaceImpl)serviceProvider.GetMefService<VisualStudioWorkspace>()) { ThreadHelper.ThrowIfNotOnUIThread(); _workspace.SubscribeExternalErrorDiagnosticUpdateSourceToSolutionBuildEvents(); } public ProjectExternalErrorReporter(ProjectId projectId, string errorCodePrefix, string language, VisualStudioWorkspaceImpl workspace) { Debug.Assert(projectId != null); Debug.Assert(errorCodePrefix != null); Debug.Assert(workspace != null); _projectId = projectId; _errorCodePrefix = errorCodePrefix; _language = language; _workspace = workspace; } private ExternalErrorDiagnosticUpdateSource DiagnosticProvider => _workspace.ExternalErrorDiagnosticUpdateSource; private bool CanHandle(string errorId) { // make sure we have error id, otherwise, we simple don't support // this error if (errorId == null) { // record NFW to see who violates contract. WatsonReporter.ReportNonFatal(new Exception("errorId is null")); return false; } // we accept all compiler diagnostics if (errorId.StartsWith(_errorCodePrefix)) { return true; } return DiagnosticProvider.IsSupportedDiagnosticId(_projectId, errorId); } public int AddNewErrors(IVsEnumExternalErrors pErrors) { var projectErrors = new HashSet<DiagnosticData>(); var documentErrorsMap = new Dictionary<DocumentId, HashSet<DiagnosticData>>(); var errors = new ExternalError[1]; while (pErrors.Next(1, errors, out var fetched) == VSConstants.S_OK && fetched == 1) { var error = errors[0]; if (error.bstrFileName != null) { var diagnostic = TryCreateDocumentDiagnosticItem(error); if (diagnostic != null) { var diagnostics = documentErrorsMap.GetOrAdd(diagnostic.DocumentId, _ => new HashSet<DiagnosticData>()); diagnostics.Add(diagnostic); continue; } } projectErrors.Add(GetDiagnosticData( documentId: null, _projectId, GetErrorId(error), error.bstrText, GetDiagnosticSeverity(error), _language, mappedFilePath: null, mappedStartLine: 0, mappedStartColumn: 0, mappedEndLine: 0, mappedEndColumn: 0, originalFilePath: null, originalStartLine: 0, originalStartColumn: 0, originalEndLine: 0, originalEndColumn: 0)); } DiagnosticProvider.AddNewErrors(_projectId, projectErrors, documentErrorsMap); return VSConstants.S_OK; } public int ClearAllErrors() { DiagnosticProvider.ClearErrors(_projectId); return VSConstants.S_OK; } public int GetErrors(out IVsEnumExternalErrors pErrors) { pErrors = null; Debug.Fail("This is not implemented, because no one called it."); return VSConstants.E_NOTIMPL; } private DocumentId TryGetDocumentId(string filePath) { return _workspace.CurrentSolution.GetDocumentIdsWithFilePath(filePath) .Where(f => f.ProjectId == _projectId) .FirstOrDefault(); } private DiagnosticData TryCreateDocumentDiagnosticItem(ExternalError error) { var documentId = TryGetDocumentId(error.bstrFileName); if (documentId == null) { return null; } var line = error.iLine; var column = error.iCol; // something we should move to document service one day. but until then, we keep the old way. // build basically output error location on surface buffer and we map it back to // subject buffer for contained document. so that contained document can map // it back to surface buffer when navigate. whole problem comes in due to the mapped span. // unlike live error, build outputs mapped span and we save it as original span (since we // have no idea whether it is mapped or not). for contained document case, we do know it is // mapped span, so we calculate original span and put that in original span. var containedDocument = ContainedDocument.TryGetContainedDocument(documentId); if (containedDocument != null) { var span = new TextSpan { iStartLine = line, iStartIndex = column, iEndLine = line, iEndIndex = column, }; var spans = new TextSpan[1]; Marshal.ThrowExceptionForHR(containedDocument.BufferCoordinator.MapPrimaryToSecondarySpan( span, spans)); line = spans[0].iStartLine; column = spans[0].iStartIndex; } // save error line/column (surface buffer location) as mapped line/column so that we can display // right location on closed Venus file. return GetDiagnosticData( documentId, _projectId, GetErrorId(error), message: error.bstrText, GetDiagnosticSeverity(error), _language, mappedFilePath: null, mappedStartLine: error.iLine, mappedStartColumn: error.iCol, mappedEndLine: error.iLine, mappedEndColumn: error.iCol, originalFilePath: error.bstrFileName, originalStartLine: line, originalStartColumn: column, originalEndLine: line, originalEndColumn: column); } public int ReportError(string bstrErrorMessage, string bstrErrorId, [ComAliasName("VsShell.VSTASKPRIORITY")] VSTASKPRIORITY nPriority, int iLine, int iColumn, string bstrFileName) { ReportError2(bstrErrorMessage, bstrErrorId, nPriority, iLine, iColumn, iLine, iColumn, bstrFileName); return VSConstants.S_OK; } // TODO: Use PreserveSig instead of throwing these exceptions for common cases. public void ReportError2(string bstrErrorMessage, string bstrErrorId, [ComAliasName("VsShell.VSTASKPRIORITY")] VSTASKPRIORITY nPriority, int iStartLine, int iStartColumn, int iEndLine, int iEndColumn, string bstrFileName) { // first we check whether given error is something we can take care. if (!CanHandle(bstrErrorId)) { // it is not, let project system take care. throw new NotImplementedException(); } if ((iEndLine >= 0 && iEndColumn >= 0) && ((iEndLine < iStartLine) || (iEndLine == iStartLine && iEndColumn < iStartColumn))) { throw new ArgumentException(ServicesVSResources.End_position_must_be_start_position); } var severity = nPriority switch { VSTASKPRIORITY.TP_HIGH => DiagnosticSeverity.Error, VSTASKPRIORITY.TP_NORMAL => DiagnosticSeverity.Warning, VSTASKPRIORITY.TP_LOW => DiagnosticSeverity.Info, _ => throw new ArgumentException(ServicesVSResources.Not_a_valid_value, nameof(nPriority)) }; DocumentId documentId; if (bstrFileName == null || iStartLine < 0 || iStartColumn < 0) { documentId = null; iStartLine = iStartColumn = iEndLine = iEndColumn = 0; } else { documentId = TryGetDocumentId(bstrFileName); } var diagnostic = GetDiagnosticData( documentId, _projectId, bstrErrorId, bstrErrorMessage, severity, language: _language, mappedFilePath: null, iStartLine, iStartColumn, iEndLine, iEndColumn, bstrFileName, iStartLine, iStartColumn, iEndLine, iEndColumn); if (documentId == null) { DiagnosticProvider.AddNewErrors(_projectId, diagnostic); } else { DiagnosticProvider.AddNewErrors(documentId, diagnostic); } } public int ClearErrors() { DiagnosticProvider.ClearErrors(_projectId); return VSConstants.S_OK; } private static DiagnosticData GetDiagnosticData( DocumentId documentId, ProjectId projectId, string errorId, string message, DiagnosticSeverity severity, string language, string mappedFilePath, int mappedStartLine, int mappedStartColumn, int mappedEndLine, int mappedEndColumn, string originalFilePath, int originalStartLine, int originalStartColumn, int originalEndLine, int originalEndColumn) { return new DiagnosticData( id: errorId, category: WellKnownDiagnosticTags.Build, message: message, title: message, enuMessageForBingSearch: message, // Unfortunately, there is no way to get ENU text for this since this is an external error. severity: severity, defaultSeverity: severity, isEnabledByDefault: true, warningLevel: (severity == DiagnosticSeverity.Error) ? 0 : 1, customTags: IsCompilerDiagnostic(errorId) ? CompilerDiagnosticCustomTags : CustomTags, properties: DiagnosticData.PropertiesForBuildDiagnostic, projectId: projectId, location: new DiagnosticDataLocation( documentId, sourceSpan: null, originalFilePath: originalFilePath, originalStartLine: originalStartLine, originalStartColumn: originalStartColumn, originalEndLine: originalEndLine, originalEndColumn: originalEndColumn, mappedFilePath: mappedFilePath, mappedStartLine: mappedStartLine, mappedStartColumn: mappedStartColumn, mappedEndLine: mappedEndLine, mappedEndColumn: mappedEndColumn), language: language); } private static bool IsCompilerDiagnostic(string errorId) { if (!string.IsNullOrEmpty(errorId) && errorId.Length > 2) { var prefix = errorId.Substring(0, 2); if (prefix.Equals("CS", StringComparison.OrdinalIgnoreCase) || prefix.Equals("BC", StringComparison.OrdinalIgnoreCase)) { var suffix = errorId.Substring(2); return int.TryParse(suffix, out _); } } return false; } private string GetErrorId(ExternalError error) => string.Format("{0}{1:0000}", _errorCodePrefix, error.iErrorID); private static DiagnosticSeverity GetDiagnosticSeverity(ExternalError error) => error.fError != 0 ? DiagnosticSeverity.Error : DiagnosticSeverity.Warning; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.Extensions; using Microsoft.VisualStudio.LanguageServices.Implementation.Venus; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.TextManager.Interop; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.TaskList { internal sealed class ProjectExternalErrorReporter : IVsReportExternalErrors, IVsLanguageServiceBuildErrorReporter2 { internal static readonly ImmutableArray<string> CustomTags = ImmutableArray.Create(WellKnownDiagnosticTags.Telemetry); internal static readonly ImmutableArray<string> CompilerDiagnosticCustomTags = ImmutableArray.Create(WellKnownDiagnosticTags.Compiler, WellKnownDiagnosticTags.Telemetry); private readonly ProjectId _projectId; private readonly string _errorCodePrefix; private readonly string _language; private readonly VisualStudioWorkspaceImpl _workspace; [Obsolete("This is a compatibility shim for F#; please do not use it.")] public ProjectExternalErrorReporter(ProjectId projectId, string errorCodePrefix, IServiceProvider serviceProvider) : this(projectId, errorCodePrefix, LanguageNames.FSharp, (VisualStudioWorkspaceImpl)serviceProvider.GetMefService<VisualStudioWorkspace>()) { ThreadHelper.ThrowIfNotOnUIThread(); _workspace.SubscribeExternalErrorDiagnosticUpdateSourceToSolutionBuildEvents(); } public ProjectExternalErrorReporter(ProjectId projectId, string errorCodePrefix, string language, VisualStudioWorkspaceImpl workspace) { Debug.Assert(projectId != null); Debug.Assert(errorCodePrefix != null); Debug.Assert(workspace != null); _projectId = projectId; _errorCodePrefix = errorCodePrefix; _language = language; _workspace = workspace; } private ExternalErrorDiagnosticUpdateSource DiagnosticProvider => _workspace.ExternalErrorDiagnosticUpdateSource; private bool CanHandle(string errorId) { // make sure we have error id, otherwise, we simple don't support // this error if (errorId == null) { // record NFW to see who violates contract. WatsonReporter.ReportNonFatal(new Exception("errorId is null")); return false; } // we accept all compiler diagnostics if (errorId.StartsWith(_errorCodePrefix)) { return true; } return DiagnosticProvider.IsSupportedDiagnosticId(_projectId, errorId); } public int AddNewErrors(IVsEnumExternalErrors pErrors) { var projectErrors = new HashSet<DiagnosticData>(); var documentErrorsMap = new Dictionary<DocumentId, HashSet<DiagnosticData>>(); var errors = new ExternalError[1]; while (pErrors.Next(1, errors, out var fetched) == VSConstants.S_OK && fetched == 1) { var error = errors[0]; if (error.bstrFileName != null) { var diagnostic = TryCreateDocumentDiagnosticItem(error); if (diagnostic != null) { var diagnostics = documentErrorsMap.GetOrAdd(diagnostic.DocumentId, _ => new HashSet<DiagnosticData>()); diagnostics.Add(diagnostic); continue; } } projectErrors.Add(GetDiagnosticData( documentId: null, _projectId, GetErrorId(error), error.bstrText, GetDiagnosticSeverity(error), _language, mappedFilePath: null, mappedStartLine: 0, mappedStartColumn: 0, mappedEndLine: 0, mappedEndColumn: 0, originalFilePath: null, originalStartLine: 0, originalStartColumn: 0, originalEndLine: 0, originalEndColumn: 0)); } DiagnosticProvider.AddNewErrors(_projectId, projectErrors, documentErrorsMap); return VSConstants.S_OK; } public int ClearAllErrors() { DiagnosticProvider.ClearErrors(_projectId); return VSConstants.S_OK; } public int GetErrors(out IVsEnumExternalErrors pErrors) { pErrors = null; Debug.Fail("This is not implemented, because no one called it."); return VSConstants.E_NOTIMPL; } private DocumentId TryGetDocumentId(string filePath) { return _workspace.CurrentSolution.GetDocumentIdsWithFilePath(filePath) .Where(f => f.ProjectId == _projectId) .FirstOrDefault(); } private DiagnosticData TryCreateDocumentDiagnosticItem(ExternalError error) { var documentId = TryGetDocumentId(error.bstrFileName); if (documentId == null) { return null; } var line = error.iLine; var column = error.iCol; // something we should move to document service one day. but until then, we keep the old way. // build basically output error location on surface buffer and we map it back to // subject buffer for contained document. so that contained document can map // it back to surface buffer when navigate. whole problem comes in due to the mapped span. // unlike live error, build outputs mapped span and we save it as original span (since we // have no idea whether it is mapped or not). for contained document case, we do know it is // mapped span, so we calculate original span and put that in original span. var containedDocument = ContainedDocument.TryGetContainedDocument(documentId); if (containedDocument != null) { var span = new TextSpan { iStartLine = line, iStartIndex = column, iEndLine = line, iEndIndex = column, }; var spans = new TextSpan[1]; Marshal.ThrowExceptionForHR(containedDocument.BufferCoordinator.MapPrimaryToSecondarySpan( span, spans)); line = spans[0].iStartLine; column = spans[0].iStartIndex; } // save error line/column (surface buffer location) as mapped line/column so that we can display // right location on closed Venus file. return GetDiagnosticData( documentId, _projectId, GetErrorId(error), message: error.bstrText, GetDiagnosticSeverity(error), _language, mappedFilePath: null, mappedStartLine: error.iLine, mappedStartColumn: error.iCol, mappedEndLine: error.iLine, mappedEndColumn: error.iCol, originalFilePath: error.bstrFileName, originalStartLine: line, originalStartColumn: column, originalEndLine: line, originalEndColumn: column); } public int ReportError(string bstrErrorMessage, string bstrErrorId, [ComAliasName("VsShell.VSTASKPRIORITY")] VSTASKPRIORITY nPriority, int iLine, int iColumn, string bstrFileName) { ReportError2(bstrErrorMessage, bstrErrorId, nPriority, iLine, iColumn, iLine, iColumn, bstrFileName); return VSConstants.S_OK; } // TODO: Use PreserveSig instead of throwing these exceptions for common cases. public void ReportError2(string bstrErrorMessage, string bstrErrorId, [ComAliasName("VsShell.VSTASKPRIORITY")] VSTASKPRIORITY nPriority, int iStartLine, int iStartColumn, int iEndLine, int iEndColumn, string bstrFileName) { // first we check whether given error is something we can take care. if (!CanHandle(bstrErrorId)) { // it is not, let project system take care. throw new NotImplementedException(); } if ((iEndLine >= 0 && iEndColumn >= 0) && ((iEndLine < iStartLine) || (iEndLine == iStartLine && iEndColumn < iStartColumn))) { throw new ArgumentException(ServicesVSResources.End_position_must_be_start_position); } var severity = nPriority switch { VSTASKPRIORITY.TP_HIGH => DiagnosticSeverity.Error, VSTASKPRIORITY.TP_NORMAL => DiagnosticSeverity.Warning, VSTASKPRIORITY.TP_LOW => DiagnosticSeverity.Info, _ => throw new ArgumentException(ServicesVSResources.Not_a_valid_value, nameof(nPriority)) }; DocumentId documentId; if (bstrFileName == null || iStartLine < 0 || iStartColumn < 0) { documentId = null; iStartLine = iStartColumn = iEndLine = iEndColumn = 0; } else { documentId = TryGetDocumentId(bstrFileName); } var diagnostic = GetDiagnosticData( documentId, _projectId, bstrErrorId, bstrErrorMessage, severity, language: _language, mappedFilePath: null, iStartLine, iStartColumn, iEndLine, iEndColumn, bstrFileName, iStartLine, iStartColumn, iEndLine, iEndColumn); if (documentId == null) { DiagnosticProvider.AddNewErrors(_projectId, diagnostic); } else { DiagnosticProvider.AddNewErrors(documentId, diagnostic); } } public int ClearErrors() { DiagnosticProvider.ClearErrors(_projectId); return VSConstants.S_OK; } private static DiagnosticData GetDiagnosticData( DocumentId documentId, ProjectId projectId, string errorId, string message, DiagnosticSeverity severity, string language, string mappedFilePath, int mappedStartLine, int mappedStartColumn, int mappedEndLine, int mappedEndColumn, string originalFilePath, int originalStartLine, int originalStartColumn, int originalEndLine, int originalEndColumn) { return new DiagnosticData( id: errorId, category: WellKnownDiagnosticTags.Build, message: message, title: message, enuMessageForBingSearch: message, // Unfortunately, there is no way to get ENU text for this since this is an external error. severity: severity, defaultSeverity: severity, isEnabledByDefault: true, warningLevel: (severity == DiagnosticSeverity.Error) ? 0 : 1, customTags: IsCompilerDiagnostic(errorId) ? CompilerDiagnosticCustomTags : CustomTags, properties: DiagnosticData.PropertiesForBuildDiagnostic, projectId: projectId, location: new DiagnosticDataLocation( documentId, sourceSpan: null, originalFilePath: originalFilePath, originalStartLine: originalStartLine, originalStartColumn: originalStartColumn, originalEndLine: originalEndLine, originalEndColumn: originalEndColumn, mappedFilePath: mappedFilePath, mappedStartLine: mappedStartLine, mappedStartColumn: mappedStartColumn, mappedEndLine: mappedEndLine, mappedEndColumn: mappedEndColumn), language: language); } private static bool IsCompilerDiagnostic(string errorId) { if (!string.IsNullOrEmpty(errorId) && errorId.Length > 2) { var prefix = errorId.Substring(0, 2); if (prefix.Equals("CS", StringComparison.OrdinalIgnoreCase) || prefix.Equals("BC", StringComparison.OrdinalIgnoreCase)) { var suffix = errorId.Substring(2); return int.TryParse(suffix, out _); } } return false; } private string GetErrorId(ExternalError error) => string.Format("{0}{1:0000}", _errorCodePrefix, error.iErrorID); private static DiagnosticSeverity GetDiagnosticSeverity(ExternalError error) => error.fError != 0 ? DiagnosticSeverity.Error : DiagnosticSeverity.Warning; } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/Workspaces/CSharp/Portable/Classification/SyntaxClassification/CSharpSyntaxClassificationService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Threading; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.Classification.Classifiers; using Microsoft.CodeAnalysis.CSharp.Classification.Classifiers; using Microsoft.CodeAnalysis.EmbeddedLanguages.LanguageServices; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Classification { internal class CSharpSyntaxClassificationService : AbstractSyntaxClassificationService { private readonly ImmutableArray<ISyntaxClassifier> s_defaultSyntaxClassifiers; [Obsolete(MefConstruction.FactoryMethodMessage, error: true)] public CSharpSyntaxClassificationService(HostLanguageServices languageServices) { var syntaxClassifiers = ImmutableArray<ISyntaxClassifier>.Empty; var embeddedLanguagesProvider = languageServices.GetService<IEmbeddedLanguagesProvider>(); if (embeddedLanguagesProvider != null) { syntaxClassifiers = syntaxClassifiers.Add(new EmbeddedLanguagesClassifier(embeddedLanguagesProvider)); } s_defaultSyntaxClassifiers = syntaxClassifiers.AddRange( new ISyntaxClassifier[] { new NameSyntaxClassifier(), new OperatorOverloadSyntaxClassifier(), new SyntaxTokenClassifier(), new UsingDirectiveSyntaxClassifier(), new DiscardSyntaxClassifier() }); } public override ImmutableArray<ISyntaxClassifier> GetDefaultSyntaxClassifiers() => s_defaultSyntaxClassifiers; public override void AddLexicalClassifications(SourceText text, TextSpan textSpan, ArrayBuilder<ClassifiedSpan> result, CancellationToken cancellationToken) => ClassificationHelpers.AddLexicalClassifications(text, textSpan, result, cancellationToken); public override void AddSyntacticClassifications(SyntaxNode root, TextSpan textSpan, ArrayBuilder<ClassifiedSpan> result, CancellationToken cancellationToken) => Worker.CollectClassifiedSpans(root, textSpan, result, cancellationToken); public override ClassifiedSpan FixClassification(SourceText rawText, ClassifiedSpan classifiedSpan) => ClassificationHelpers.AdjustStaleClassification(rawText, classifiedSpan); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Threading; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.Classification.Classifiers; using Microsoft.CodeAnalysis.CSharp.Classification.Classifiers; using Microsoft.CodeAnalysis.EmbeddedLanguages.LanguageServices; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Classification { internal class CSharpSyntaxClassificationService : AbstractSyntaxClassificationService { private readonly ImmutableArray<ISyntaxClassifier> s_defaultSyntaxClassifiers; [Obsolete(MefConstruction.FactoryMethodMessage, error: true)] public CSharpSyntaxClassificationService(HostLanguageServices languageServices) { var syntaxClassifiers = ImmutableArray<ISyntaxClassifier>.Empty; var embeddedLanguagesProvider = languageServices.GetService<IEmbeddedLanguagesProvider>(); if (embeddedLanguagesProvider != null) { syntaxClassifiers = syntaxClassifiers.Add(new EmbeddedLanguagesClassifier(embeddedLanguagesProvider)); } s_defaultSyntaxClassifiers = syntaxClassifiers.AddRange( new ISyntaxClassifier[] { new NameSyntaxClassifier(), new OperatorOverloadSyntaxClassifier(), new SyntaxTokenClassifier(), new UsingDirectiveSyntaxClassifier(), new DiscardSyntaxClassifier() }); } public override ImmutableArray<ISyntaxClassifier> GetDefaultSyntaxClassifiers() => s_defaultSyntaxClassifiers; public override void AddLexicalClassifications(SourceText text, TextSpan textSpan, ArrayBuilder<ClassifiedSpan> result, CancellationToken cancellationToken) => ClassificationHelpers.AddLexicalClassifications(text, textSpan, result, cancellationToken); public override void AddSyntacticClassifications(SyntaxNode root, TextSpan textSpan, ArrayBuilder<ClassifiedSpan> result, CancellationToken cancellationToken) => Worker.CollectClassifiedSpans(root, textSpan, result, cancellationToken); public override ClassifiedSpan FixClassification(SourceText rawText, ClassifiedSpan classifiedSpan) => ClassificationHelpers.AdjustStaleClassification(rawText, classifiedSpan); } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/VisualStudio/Core/Def/Interactive/AbstractResetInteractiveCommand.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using EnvDTE; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.LanguageServices; using Microsoft.VisualStudio.LanguageServices.Interactive; using Microsoft.VisualStudio.Shell.Interop; using System; namespace Roslyn.VisualStudio.Services.Interactive { internal abstract class AbstractResetInteractiveCommand : IResetInteractiveCommand { private readonly VisualStudioWorkspace _workspace; private readonly IComponentModel _componentModel; private readonly VsInteractiveWindowProvider _interactiveWindowProvider; private readonly IServiceProvider _serviceProvider; protected abstract string LanguageName { get; } protected abstract string CreateReference(string referenceName); protected abstract string CreateImport(string namespaceName); public AbstractResetInteractiveCommand( VisualStudioWorkspace workspace, VsInteractiveWindowProvider interactiveWindowProvider, IServiceProvider serviceProvider) { _workspace = workspace; _interactiveWindowProvider = interactiveWindowProvider; _serviceProvider = serviceProvider; _componentModel = (IComponentModel)GetService(typeof(SComponentModel)); } private object GetService(Type type) => _serviceProvider.GetService(type); public void ExecuteResetInteractive() { var resetInteractive = new VsResetInteractive( _workspace, (DTE)GetService(typeof(SDTE)), _componentModel, (IVsMonitorSelection)GetService(typeof(SVsShellMonitorSelection)), (IVsSolutionBuildManager)GetService(typeof(SVsSolutionBuildManager)), CreateReference, CreateImport); var vsInteractiveWindow = _interactiveWindowProvider.Open(instanceId: 0, focus: true); void focusWindow(object s, EventArgs e) { // We have to set focus to the Interactive Window *after* the wait indicator is dismissed. vsInteractiveWindow.Show(focus: true); resetInteractive.ExecutionCompleted -= focusWindow; } resetInteractive.ExecuteAsync(vsInteractiveWindow.InteractiveWindow, LanguageName + " Interactive"); resetInteractive.ExecutionCompleted += focusWindow; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using EnvDTE; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.LanguageServices; using Microsoft.VisualStudio.LanguageServices.Interactive; using Microsoft.VisualStudio.Shell.Interop; using System; namespace Roslyn.VisualStudio.Services.Interactive { internal abstract class AbstractResetInteractiveCommand : IResetInteractiveCommand { private readonly VisualStudioWorkspace _workspace; private readonly IComponentModel _componentModel; private readonly VsInteractiveWindowProvider _interactiveWindowProvider; private readonly IServiceProvider _serviceProvider; protected abstract string LanguageName { get; } protected abstract string CreateReference(string referenceName); protected abstract string CreateImport(string namespaceName); public AbstractResetInteractiveCommand( VisualStudioWorkspace workspace, VsInteractiveWindowProvider interactiveWindowProvider, IServiceProvider serviceProvider) { _workspace = workspace; _interactiveWindowProvider = interactiveWindowProvider; _serviceProvider = serviceProvider; _componentModel = (IComponentModel)GetService(typeof(SComponentModel)); } private object GetService(Type type) => _serviceProvider.GetService(type); public void ExecuteResetInteractive() { var resetInteractive = new VsResetInteractive( _workspace, (DTE)GetService(typeof(SDTE)), _componentModel, (IVsMonitorSelection)GetService(typeof(SVsShellMonitorSelection)), (IVsSolutionBuildManager)GetService(typeof(SVsSolutionBuildManager)), CreateReference, CreateImport); var vsInteractiveWindow = _interactiveWindowProvider.Open(instanceId: 0, focus: true); void focusWindow(object s, EventArgs e) { // We have to set focus to the Interactive Window *after* the wait indicator is dismissed. vsInteractiveWindow.Show(focus: true); resetInteractive.ExecutionCompleted -= focusWindow; } resetInteractive.ExecuteAsync(vsInteractiveWindow.InteractiveWindow, LanguageName + " Interactive"); resetInteractive.ExecutionCompleted += focusWindow; } } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/Workspaces/Core/Portable/SymbolKey/SymbolKey.PropertySymbolKey.cs
// Licensed to the .NET Foundation under one or more 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 { internal partial struct SymbolKey { private static class PropertySymbolKey { public static void Create(IPropertySymbol symbol, SymbolKeyWriter visitor) { visitor.WriteString(symbol.MetadataName); visitor.WriteSymbolKey(symbol.ContainingSymbol); visitor.WriteBoolean(symbol.IsIndexer); visitor.WriteRefKindArray(symbol.Parameters); visitor.WriteParameterTypesArray(symbol.OriginalDefinition.Parameters); } public static SymbolKeyResolution Resolve(SymbolKeyReader reader, out string? failureReason) { var metadataName = reader.ReadString(); var containingTypeResolution = reader.ReadSymbolKey(out var containingTypeFailureReason); var isIndexer = reader.ReadBoolean(); using var refKinds = reader.ReadRefKindArray(); using var parameterTypes = reader.ReadSymbolKeyArray<ITypeSymbol>(out var parameterTypesFailureReason); if (containingTypeFailureReason != null) { failureReason = $"({nameof(PropertySymbolKey)} {nameof(containingTypeResolution)} failed -> {containingTypeFailureReason})"; return default; } if (parameterTypesFailureReason != null) { failureReason = $"({nameof(PropertySymbolKey)} {nameof(parameterTypes)} failed -> {parameterTypesFailureReason})"; return default; } if (parameterTypes.IsDefault) { failureReason = $"({nameof(PropertySymbolKey)} no parameter types)"; return default; } using var properties = GetMembersOfNamedType<IPropertySymbol>(containingTypeResolution, metadataName: null); using var result = PooledArrayBuilder<IPropertySymbol>.GetInstance(); foreach (var property in properties) { if (property.Parameters.Length == refKinds.Count && property.MetadataName == metadataName && property.IsIndexer == isIndexer && ParameterRefKindsMatch(property.OriginalDefinition.Parameters, refKinds) && reader.ParameterTypesMatch(property.OriginalDefinition.Parameters, parameterTypes)) { result.AddIfNotNull(property); } } return CreateResolution(result, $"({nameof(PropertySymbolKey)} '{metadataName}' not found)", out failureReason); } } } }
// Licensed to the .NET Foundation under one or more 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 { internal partial struct SymbolKey { private static class PropertySymbolKey { public static void Create(IPropertySymbol symbol, SymbolKeyWriter visitor) { visitor.WriteString(symbol.MetadataName); visitor.WriteSymbolKey(symbol.ContainingSymbol); visitor.WriteBoolean(symbol.IsIndexer); visitor.WriteRefKindArray(symbol.Parameters); visitor.WriteParameterTypesArray(symbol.OriginalDefinition.Parameters); } public static SymbolKeyResolution Resolve(SymbolKeyReader reader, out string? failureReason) { var metadataName = reader.ReadString(); var containingTypeResolution = reader.ReadSymbolKey(out var containingTypeFailureReason); var isIndexer = reader.ReadBoolean(); using var refKinds = reader.ReadRefKindArray(); using var parameterTypes = reader.ReadSymbolKeyArray<ITypeSymbol>(out var parameterTypesFailureReason); if (containingTypeFailureReason != null) { failureReason = $"({nameof(PropertySymbolKey)} {nameof(containingTypeResolution)} failed -> {containingTypeFailureReason})"; return default; } if (parameterTypesFailureReason != null) { failureReason = $"({nameof(PropertySymbolKey)} {nameof(parameterTypes)} failed -> {parameterTypesFailureReason})"; return default; } if (parameterTypes.IsDefault) { failureReason = $"({nameof(PropertySymbolKey)} no parameter types)"; return default; } using var properties = GetMembersOfNamedType<IPropertySymbol>(containingTypeResolution, metadataName: null); using var result = PooledArrayBuilder<IPropertySymbol>.GetInstance(); foreach (var property in properties) { if (property.Parameters.Length == refKinds.Count && property.MetadataName == metadataName && property.IsIndexer == isIndexer && ParameterRefKindsMatch(property.OriginalDefinition.Parameters, refKinds) && reader.ParameterTypesMatch(property.OriginalDefinition.Parameters, parameterTypes)) { result.AddIfNotNull(property); } } return CreateResolution(result, $"({nameof(PropertySymbolKey)} '{metadataName}' not found)", out failureReason); } } } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/Features/CSharp/Portable/ExtractMethod/CSharpMethodExtractor.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.ExtractMethod; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.ExtractMethod { internal partial class CSharpMethodExtractor : MethodExtractor { public CSharpMethodExtractor(CSharpSelectionResult result, bool localFunction) : base(result, localFunction) { } protected override Task<AnalyzerResult> AnalyzeAsync(SelectionResult selectionResult, bool localFunction, CancellationToken cancellationToken) => CSharpAnalyzer.AnalyzeAsync(selectionResult, localFunction, cancellationToken); protected override async Task<InsertionPoint> GetInsertionPointAsync(SemanticDocument document, CancellationToken cancellationToken) { var originalSpanStart = OriginalSelectionResult.OriginalSpan.Start; Contract.ThrowIfFalse(originalSpanStart >= 0); var root = await document.Document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var basePosition = root.FindToken(originalSpanStart); if (LocalFunction) { // If we are extracting a local function and are within a local function, then we want the new function to be created within the // existing local function instead of the overarching method. var localFunctionNode = basePosition.GetAncestor<LocalFunctionStatementSyntax>(node => (node.Body != null && node.Body.Span.Contains(OriginalSelectionResult.OriginalSpan)) || (node.ExpressionBody != null && node.ExpressionBody.Span.Contains(OriginalSelectionResult.OriginalSpan))); if (localFunctionNode is object) { return await InsertionPoint.CreateAsync(document, localFunctionNode, cancellationToken).ConfigureAwait(false); } } var memberNode = basePosition.GetAncestor<MemberDeclarationSyntax>(); Contract.ThrowIfNull(memberNode); Contract.ThrowIfTrue(memberNode.Kind() == SyntaxKind.NamespaceDeclaration); if (LocalFunction && memberNode is BasePropertyDeclarationSyntax propertyDeclaration) { var accessorNode = basePosition.GetAncestor<AccessorDeclarationSyntax>(); if (accessorNode is object) { return await InsertionPoint.CreateAsync(document, accessorNode, cancellationToken).ConfigureAwait(false); } } if (memberNode is GlobalStatementSyntax globalStatement) { // check whether we are extracting whole global statement out if (OriginalSelectionResult.FinalSpan.Contains(memberNode.Span)) { return await InsertionPoint.CreateAsync(document, globalStatement.Parent, cancellationToken).ConfigureAwait(false); } // check whether the global statement is a statement container if (!globalStatement.Statement.IsStatementContainerNode() && !root.SyntaxTree.IsScript()) { // The extracted function will be a new global statement return await InsertionPoint.CreateAsync(document, globalStatement.Parent, cancellationToken).ConfigureAwait(false); } return await InsertionPoint.CreateAsync(document, globalStatement.Statement, cancellationToken).ConfigureAwait(false); } return await InsertionPoint.CreateAsync(document, memberNode, cancellationToken).ConfigureAwait(false); } protected override async Task<TriviaResult> PreserveTriviaAsync(SelectionResult selectionResult, CancellationToken cancellationToken) => await CSharpTriviaResult.ProcessAsync(selectionResult, cancellationToken).ConfigureAwait(false); protected override async Task<SemanticDocument> ExpandAsync(SelectionResult selection, CancellationToken cancellationToken) { var lastExpression = selection.GetFirstTokenInSelection().GetCommonRoot(selection.GetLastTokenInSelection()).GetAncestors<ExpressionSyntax>().LastOrDefault(); if (lastExpression == null) { return selection.SemanticDocument; } var newExpression = await Simplifier.ExpandAsync(lastExpression, selection.SemanticDocument.Document, n => n != selection.GetContainingScope(), expandParameter: false, cancellationToken: cancellationToken).ConfigureAwait(false); return await selection.SemanticDocument.WithSyntaxRootAsync(selection.SemanticDocument.Root.ReplaceNode(lastExpression, newExpression), cancellationToken).ConfigureAwait(false); } protected override Task<GeneratedCode> GenerateCodeAsync(InsertionPoint insertionPoint, SelectionResult selectionResult, AnalyzerResult analyzeResult, OptionSet options, CancellationToken cancellationToken) => CSharpCodeGenerator.GenerateAsync(insertionPoint, selectionResult, analyzeResult, options, LocalFunction, cancellationToken); protected override IEnumerable<AbstractFormattingRule> GetFormattingRules(Document document) => SpecializedCollections.SingletonEnumerable(new FormattingRule()).Concat(Formatter.GetDefaultFormattingRules(document)); protected override SyntaxToken GetMethodNameAtInvocation(IEnumerable<SyntaxNodeOrToken> methodNames) => (SyntaxToken)methodNames.FirstOrDefault(t => !t.Parent.IsKind(SyntaxKind.MethodDeclaration)); protected override async Task<OperationStatus> CheckTypeAsync( Document document, SyntaxNode contextNode, Location location, ITypeSymbol type, CancellationToken cancellationToken) { Contract.ThrowIfNull(type); // this happens when there is no return type if (type.SpecialType == SpecialType.System_Void) { return OperationStatus.Succeeded; } if (type.TypeKind is TypeKind.Error or TypeKind.Unknown) { return OperationStatus.ErrorOrUnknownType; } // if it is type parameter, make sure we are getting same type parameter var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); foreach (var typeParameter in TypeParameterCollector.Collect(type)) { var typeName = SyntaxFactory.ParseTypeName(typeParameter.Name); var currentType = semanticModel.GetSpeculativeTypeInfo(contextNode.SpanStart, typeName, SpeculativeBindingOption.BindAsTypeOrNamespace).Type; if (currentType == null || !SymbolEqualityComparer.Default.Equals(currentType, typeParameter)) { return new OperationStatus(OperationStatusFlag.BestEffort, string.Format(FeaturesResources.Type_parameter_0_is_hidden_by_another_type_parameter_1, typeParameter.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat), currentType == null ? string.Empty : currentType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat))); } } return OperationStatus.Succeeded; } protected override async Task<(Document document, SyntaxToken methodName, SyntaxNode methodDefinition)> InsertNewLineBeforeLocalFunctionIfNecessaryAsync( Document document, SyntaxToken methodName, SyntaxNode methodDefinition, CancellationToken cancellationToken) { // Checking to see if there is already an empty line before the local method declaration. var leadingTrivia = methodDefinition.GetLeadingTrivia(); if (!leadingTrivia.Any(t => t.IsKind(SyntaxKind.EndOfLineTrivia)) && !methodDefinition.FindTokenOnLeftOfPosition(methodDefinition.SpanStart).IsKind(SyntaxKind.OpenBraceToken)) { var originalMethodDefinition = methodDefinition; methodDefinition = methodDefinition.WithPrependedLeadingTrivia(SpecializedCollections.SingletonEnumerable(SyntaxFactory.CarriageReturnLineFeed)); // Generating the new document and associated variables. var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); document = document.WithSyntaxRoot(root.ReplaceNode(originalMethodDefinition, methodDefinition)); var newRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); methodName = newRoot.FindToken(methodName.SpanStart); } return (document, methodName, methodDefinition); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.ExtractMethod; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.ExtractMethod { internal partial class CSharpMethodExtractor : MethodExtractor { public CSharpMethodExtractor(CSharpSelectionResult result, bool localFunction) : base(result, localFunction) { } protected override Task<AnalyzerResult> AnalyzeAsync(SelectionResult selectionResult, bool localFunction, CancellationToken cancellationToken) => CSharpAnalyzer.AnalyzeAsync(selectionResult, localFunction, cancellationToken); protected override async Task<InsertionPoint> GetInsertionPointAsync(SemanticDocument document, CancellationToken cancellationToken) { var originalSpanStart = OriginalSelectionResult.OriginalSpan.Start; Contract.ThrowIfFalse(originalSpanStart >= 0); var root = await document.Document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var basePosition = root.FindToken(originalSpanStart); if (LocalFunction) { // If we are extracting a local function and are within a local function, then we want the new function to be created within the // existing local function instead of the overarching method. var localFunctionNode = basePosition.GetAncestor<LocalFunctionStatementSyntax>(node => (node.Body != null && node.Body.Span.Contains(OriginalSelectionResult.OriginalSpan)) || (node.ExpressionBody != null && node.ExpressionBody.Span.Contains(OriginalSelectionResult.OriginalSpan))); if (localFunctionNode is object) { return await InsertionPoint.CreateAsync(document, localFunctionNode, cancellationToken).ConfigureAwait(false); } } var memberNode = basePosition.GetAncestor<MemberDeclarationSyntax>(); Contract.ThrowIfNull(memberNode); Contract.ThrowIfTrue(memberNode.Kind() == SyntaxKind.NamespaceDeclaration); if (LocalFunction && memberNode is BasePropertyDeclarationSyntax propertyDeclaration) { var accessorNode = basePosition.GetAncestor<AccessorDeclarationSyntax>(); if (accessorNode is object) { return await InsertionPoint.CreateAsync(document, accessorNode, cancellationToken).ConfigureAwait(false); } } if (memberNode is GlobalStatementSyntax globalStatement) { // check whether we are extracting whole global statement out if (OriginalSelectionResult.FinalSpan.Contains(memberNode.Span)) { return await InsertionPoint.CreateAsync(document, globalStatement.Parent, cancellationToken).ConfigureAwait(false); } // check whether the global statement is a statement container if (!globalStatement.Statement.IsStatementContainerNode() && !root.SyntaxTree.IsScript()) { // The extracted function will be a new global statement return await InsertionPoint.CreateAsync(document, globalStatement.Parent, cancellationToken).ConfigureAwait(false); } return await InsertionPoint.CreateAsync(document, globalStatement.Statement, cancellationToken).ConfigureAwait(false); } return await InsertionPoint.CreateAsync(document, memberNode, cancellationToken).ConfigureAwait(false); } protected override async Task<TriviaResult> PreserveTriviaAsync(SelectionResult selectionResult, CancellationToken cancellationToken) => await CSharpTriviaResult.ProcessAsync(selectionResult, cancellationToken).ConfigureAwait(false); protected override async Task<SemanticDocument> ExpandAsync(SelectionResult selection, CancellationToken cancellationToken) { var lastExpression = selection.GetFirstTokenInSelection().GetCommonRoot(selection.GetLastTokenInSelection()).GetAncestors<ExpressionSyntax>().LastOrDefault(); if (lastExpression == null) { return selection.SemanticDocument; } var newExpression = await Simplifier.ExpandAsync(lastExpression, selection.SemanticDocument.Document, n => n != selection.GetContainingScope(), expandParameter: false, cancellationToken: cancellationToken).ConfigureAwait(false); return await selection.SemanticDocument.WithSyntaxRootAsync(selection.SemanticDocument.Root.ReplaceNode(lastExpression, newExpression), cancellationToken).ConfigureAwait(false); } protected override Task<GeneratedCode> GenerateCodeAsync(InsertionPoint insertionPoint, SelectionResult selectionResult, AnalyzerResult analyzeResult, OptionSet options, CancellationToken cancellationToken) => CSharpCodeGenerator.GenerateAsync(insertionPoint, selectionResult, analyzeResult, options, LocalFunction, cancellationToken); protected override IEnumerable<AbstractFormattingRule> GetFormattingRules(Document document) => SpecializedCollections.SingletonEnumerable(new FormattingRule()).Concat(Formatter.GetDefaultFormattingRules(document)); protected override SyntaxToken GetMethodNameAtInvocation(IEnumerable<SyntaxNodeOrToken> methodNames) => (SyntaxToken)methodNames.FirstOrDefault(t => !t.Parent.IsKind(SyntaxKind.MethodDeclaration)); protected override async Task<OperationStatus> CheckTypeAsync( Document document, SyntaxNode contextNode, Location location, ITypeSymbol type, CancellationToken cancellationToken) { Contract.ThrowIfNull(type); // this happens when there is no return type if (type.SpecialType == SpecialType.System_Void) { return OperationStatus.Succeeded; } if (type.TypeKind is TypeKind.Error or TypeKind.Unknown) { return OperationStatus.ErrorOrUnknownType; } // if it is type parameter, make sure we are getting same type parameter var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); foreach (var typeParameter in TypeParameterCollector.Collect(type)) { var typeName = SyntaxFactory.ParseTypeName(typeParameter.Name); var currentType = semanticModel.GetSpeculativeTypeInfo(contextNode.SpanStart, typeName, SpeculativeBindingOption.BindAsTypeOrNamespace).Type; if (currentType == null || !SymbolEqualityComparer.Default.Equals(currentType, typeParameter)) { return new OperationStatus(OperationStatusFlag.BestEffort, string.Format(FeaturesResources.Type_parameter_0_is_hidden_by_another_type_parameter_1, typeParameter.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat), currentType == null ? string.Empty : currentType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat))); } } return OperationStatus.Succeeded; } protected override async Task<(Document document, SyntaxToken methodName, SyntaxNode methodDefinition)> InsertNewLineBeforeLocalFunctionIfNecessaryAsync( Document document, SyntaxToken methodName, SyntaxNode methodDefinition, CancellationToken cancellationToken) { // Checking to see if there is already an empty line before the local method declaration. var leadingTrivia = methodDefinition.GetLeadingTrivia(); if (!leadingTrivia.Any(t => t.IsKind(SyntaxKind.EndOfLineTrivia)) && !methodDefinition.FindTokenOnLeftOfPosition(methodDefinition.SpanStart).IsKind(SyntaxKind.OpenBraceToken)) { var originalMethodDefinition = methodDefinition; methodDefinition = methodDefinition.WithPrependedLeadingTrivia(SpecializedCollections.SingletonEnumerable(SyntaxFactory.CarriageReturnLineFeed)); // Generating the new document and associated variables. var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); document = document.WithSyntaxRoot(root.ReplaceNode(originalMethodDefinition, methodDefinition)); var newRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); methodName = newRoot.FindToken(methodName.SpanStart); } return (document, methodName, methodDefinition); } } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/EditorFeatures/CSharpTest/RefactoringHelpers/RefactoringHelpersTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.CSharp.Syntax; using Microsoft.CodeAnalysis.Editor.UnitTests.RefactoringHelpers; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.RefactoringHelpers { public partial class RefactoringHelpersTests : RefactoringHelpersTestBase<CSharpTestWorkspaceFixture> { #region Locations [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestInTokenDirectlyUnderNode() { var testText = @" class C { void M() { {|result:C Local[||]Function(C c) { return null; }|} } }"; await TestAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestBeforeTokenDirectlyUnderNode() { var testText = @" class C { void M() { {|result:C [||]LocalFunction(C c) { return null; }|} } }"; await TestAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestAfterTokenDirectlyUnderNode() { var testText = @" class C { void M() { {|result:C [||]LocalFunction(C c) { return null; }|} } }"; await TestAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingInTokenUnderDifferentNode() { var testText = @" class C { void M() { C LocalFunction(C c) { [||]return null; } } }"; await TestMissingAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestClimbRightEdge() { var testText = @" class C { void M() { {|result:C LocalFunction(C c) { return null; }[||]|} } }"; await TestAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestClimbLeftEdge() { var testText = @" class C { void M() { {|result:[||]C LocalFunction(C c) { return null; }|} } }"; await TestAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestClimbLeftEdgeComments() { var testText = @" class C { void M() { /// <summary> /// Comment1 /// </summary> {|result:[||]C LocalFunction(C c) { return null; }|} } }"; await TestAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingInAnotherChildNode() { var testText = @" class C { void M() { C LocalFunction(C c) { [||]return null; } } }"; await TestMissingAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingInTooFarBeforeInWhitespace() { var testText = @" class C { void M() { [||] C LocalFunction(C c) { return null; } } }"; await TestMissingAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingInWhiteSpaceOnLineWithDifferentStatement() { var testText = @" class C { void M() { var a = null; [||] C LocalFunction(C c) { return null; } } }"; await TestMissingAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestNotBeforePrecedingComment() { var testText = @" class C { void M() { [||]//Test comment C LocalFunction(C c) { return null; } } }"; await TestMissingAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestBeforeInWhitespace1_OnSameLine() { var testText = @" class C { void M() { [||] {|result:C LocalFunction(C c) { return null; }|} } }"; await TestAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestBeforeInWhitespace1_OnPreviousLine() { var testText = @" class C { void M() { [||] {|result:C LocalFunction(C c) { return null; }|} } }"; await TestAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestBeforeInWhitespace1_NotOnMultipleLinesPrior() { var testText = @" class C { void M() { [||] C LocalFunction(C c) { return null; } } }"; await TestMissingAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestBeforeInWhitespace2() { var testText = @" class C { void M() { var a = null; [||] {|result:C LocalFunction(C c) { return null; }|} } }"; await TestAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingInNextTokensLeadingTrivia() { var testText = @" class C { void M() { C LocalFunction(C c) { return null; } [||] } }"; await TestMissingAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestInEmptySyntaxNode() { var testText = @" class C { void M() { N(0, N(0, [||]{|result:|}, 0)); } int N(int a, int b, int c) { } }"; await TestAsync<ArgumentSyntax>(testText); } #endregion #region Selections [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestSelectedTokenDirectlyUnderNode() { var testText = @" class C { void M() { {|result:C [|LocalFunction|](C c) { return null; }|} } }"; await TestAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestPartiallySelectedTokenDirectlyUnderNode() { var testText = @" class C { void M() { {|result:C Lo[|calFunct|]ion(C c) { return null; }|} } }"; await TestAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestSelectedMultipleTokensUnderNode() { var testText = @" class C { void M() { {|result:[|C LocalFunction(C c)|] { return null; }|} } }"; await TestAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingSelectedMultipleTokensWithLowerCommonAncestor() { var testText = @" class C { void M() { C LocalFunction(C c) [|{ return null; }|] } }"; await TestMissingAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingSelectedLowerNode() { var testText = @" class C { void M() { [|C|] LocalFunction(C c) { return null; } } }"; await TestMissingAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingSelectedWhitespace() { var testText = @" class C { void M() { C[| |]LocalFunction(C c) { return null; } } }"; await TestMissingAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingSelectedWhitespace2() { var testText = @" class C { void M() { [| |]C LocalFunction(C c) { return null; } } }"; await TestMissingAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestCompleteSelection() { var testText = @" class C { void M() { {|result:[|C LocalFunction(C c) { return null; }|]|} } }"; await TestAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestOverSelection() { var testText = @" class C { void M() { [| {|result:C LocalFunction(C c) { return null; }|} |]var a = new object(); } }"; await TestAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestOverSelectionComments() { var testText = @" class C { void M() { // Co[|mment1 {|result:C LocalFunction(C c) { return null; }|}|] } }"; await TestAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingOverSelection() { var testText = @" class C { void M() { [| C LocalFunction(C c) { return null; } v|]ar a = new object(); } }"; await TestMissingAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingSelectionBefore() { var testText = @" class C { void M() { [| |]C LocalFunction(C c) { return null; } var a = new object(); } }"; await TestMissingAsync<LocalFunctionStatementSyntax>(testText); } #endregion #region IsUnderselected [Fact] [WorkItem(38708, "https://github.com/dotnet/roslyn/issues/38708")] public async Task TestUnderselectionOnSemicolon() { var testText = @" class Program { static void Main() { {|result:Main()|}[|;|] } }"; await TestNotUnderselectedAsync<ExpressionSyntax>(testText); } [Fact] [WorkItem(38708, "https://github.com/dotnet/roslyn/issues/38708")] public async Task TestUnderselectionBug1() { var testText = @" class Program { public static void Method() { //[|> var str = {|result:"" <|] aaa""|}; } }"; await TestNotUnderselectedAsync<ExpressionSyntax>(testText); } [Fact] [WorkItem(38708, "https://github.com/dotnet/roslyn/issues/38708")] public async Task TestUnderselectionBug2() { var testText = @" class C { public void M() { Console.WriteLine(""Hello world"");[| {|result:Console.WriteLine(new |]C())|}; } }"; await TestNotUnderselectedAsync<ExpressionSyntax>(testText); } [Fact] [WorkItem(38708, "https://github.com/dotnet/roslyn/issues/38708")] public async Task TestUnderselection() { var testText = @" class C { public void M() { bool a = {|result:[|true || false || true|]|}; }"; await TestNotUnderselectedAsync<BinaryExpressionSyntax>(testText); } [Fact] [WorkItem(38708, "https://github.com/dotnet/roslyn/issues/38708")] public async Task TestUnderselection2() { var testText = @" class C { public void M() { bool a = true || [|false || true|] || true; }"; await TestUnderselectedAsync<BinaryExpressionSyntax>(testText); } #endregion #region Attributes [Fact] [WorkItem(37584, "https://github.com/dotnet/roslyn/issues/37584")] public async Task TestMissingEmptyMember() { var testText = @" using System; public class Class1 { [][||] }"; await TestMissingAsync<MethodDeclarationSyntax>(testText); } [Fact] [WorkItem(38502, "https://github.com/dotnet/roslyn/issues/38502")] public async Task TestIncompleteAttribute() { var testText = @" using System; public class Class1 { {|result:void foo([[||]bar) {}|} }"; await TestAsync<MethodDeclarationSyntax>(testText); } [Fact] [WorkItem(38502, "https://github.com/dotnet/roslyn/issues/38502")] public async Task TestIncompleteAttribute2() { var testText = @" using System; public class Class1 { {|result:void foo([[||]Class1 arg1) {}|} }"; await TestAsync<MethodDeclarationSyntax>(testText); } [Fact] [WorkItem(37837, "https://github.com/dotnet/roslyn/issues/37837")] public async Task TestEmptyParameter() { var testText = @" using System; public class TestAttribute : Attribute { } public class Class1 { static void foo({|result:[Test][||] |} { } }"; await TestAsync<ParameterSyntax>(testText); } [Fact] [WorkItem(37584, "https://github.com/dotnet/roslyn/issues/37584")] public async Task TestMissingEmptyMember2() { var testText = @" using System; public class Class1 { [||]// Comment [] }"; await TestMissingAsync<MethodDeclarationSyntax>(testText); } [Fact] [WorkItem(37584, "https://github.com/dotnet/roslyn/issues/37584")] public async Task TestEmptyAttributeList() { var testText = @" using System; public class Class1 { {|result:[] [||]void a() {}|} }"; await TestAsync<MethodDeclarationSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestClimbLeftEdgeBeforeAttribute() { var testText = @" using System; class C { class TestAttribute : Attribute { } // Comment1 [||]{|result:[Test] void M() { }|} }"; await TestAsync<MethodDeclarationSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestClimbLeftEdgeAfterAttribute() { var testText = @" using System; class C { class TestAttribute : Attribute { } {|result:[Test] [||]void M() { }|} }"; await TestAsync<MethodDeclarationSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestClimbLeftEdgeAfterAttributeComments() { var testText = @" using System; class C { class TestAttribute : Attribute { } // Comment1 {|result:[Test] // Comment2 [||]void M() { }|} }"; await TestAsync<MethodDeclarationSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestClimbLeftEdgeAfterAttributes() { var testText = @" using System; class C { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } // Comment1 {|result:[Test] [Test2] // Comment2 [||]void M() { }|} }"; await TestAsync<MethodDeclarationSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingBetweenAttributes() { var testText = @" using System; class C { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } [Test] [||][Test2] void M() { } }"; await TestMissingAsync<MethodDeclarationSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingBetweenInAttributes() { var testText = @" using System; class C { class TestAttribute : Attribute { } [[||]Test] void M() { } }"; await TestMissingAsync<MethodDeclarationSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingSelectedAttributes() { var testText = @" using System; class C { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } [|[Test] [Test2]|] void M() { } }"; await TestMissingAsync<MethodDeclarationSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingSelectedAttribute() { var testText = @" using System; class C { class TestAttribute : Attribute { } [|[Test]|] void M() { } }"; await TestMissingAsync<MethodDeclarationSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestSelectedWholeNodeAndAttributes() { var testText = @" using System; class C { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } // Comment1 [|{|result:[Test] [Test2] // Comment2 void M() { }|}|] }"; await TestAsync<MethodDeclarationSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestSelectedWholeNodeWithoutAttributes() { var testText = @" using System; class C { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } // Comment1 {|result:[Test] [Test2] // Comment2 [|void M() { }|]|} }"; await TestAsync<MethodDeclarationSyntax>(testText); } #endregion #region Extractions general [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestExtractionsClimbing() { var testText = @" using System; class C { void M() { var a = {|result:new object()|};[||] } }"; await TestAsync<ObjectCreationExpressionSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingExtractHeaderForSelection() { var testText = @" using System; class C { class TestAttribute : Attribute { } [Test] public [|int|] a { get; set; } }"; await TestMissingAsync<PropertyDeclarationSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMultipleExtractions() { var localDeclaration = "{|result:string name = \"\", b[||]b = null;|}"; var localDeclarator = "string name = \"\", {|result:bb[||] = null|};"; await TestAsync<LocalDeclarationStatementSyntax>(GetTestText(localDeclaration)); await TestAsync<VariableDeclaratorSyntax>(GetTestText(localDeclarator)); static string GetTestText(string data) { return @" class C { void M() { C LocalFunction(C c) { " + data + @"return null; } var a = new object(); } }"; } } #endregion #region Extractions [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestExtractFromDeclaration() { var testText = @" using System; class C { void M() { [|var a = {|result:new object()|};|] } }"; await TestAsync<ObjectCreationExpressionSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestExtractFromDeclaration2() { var testText = @" using System; class C { void M() { var a = [|{|result:new object()|};|] } }"; await TestAsync<ObjectCreationExpressionSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestExtractFromAssignment() { var testText = @" using System; class C { void M() { object a; a = [|{|result:new object()|};|] } }"; await TestAsync<ObjectCreationExpressionSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestExtractFromDeclarator() { var testText = @" using System; class C { void M() { var [|a = {|result:new object()|}|]; } }"; await TestAsync<ObjectCreationExpressionSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestExtractFromDeclarator2() { var testText = @" using System; class C { void M() { {|result:var [|a = new object()|];|} } }"; await TestAsync<LocalDeclarationStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestExtractInHeaderOfProperty() { var testText = @" using System; class C { class TestAttribute : Attribute { } {|result:[Test] public i[||]nt a { get; set; }|} }"; await TestAsync<PropertyDeclarationSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingExtractNotInHeaderOfProperty() { var testText = @" using System; class C { class TestAttribute : Attribute { } [Test] public int a { [||]get; set; } }"; await TestMissingAsync<PropertyDeclarationSyntax>(testText); } #endregion #region Headers & holes [Theory] [InlineData("var aa = nul[||]l;")] [InlineData("var aa = n[||]ull;")] [InlineData("string aa = null, bb = n[||]ull;")] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingInHeaderHole(string data) { var testText = @" class C { void M() { C LocalFunction(C c) { " + data + @"return null; } var a = new object(); } }"; await TestMissingAsync<LocalDeclarationStatementSyntax>(testText); } [Theory] [InlineData("{|result:[||]var aa = null;|}")] [InlineData("{|result:var aa = [||]null;|}")] [InlineData("{|result:var aa = null[||];|}")] [InlineData("{|result:string aa = null, b[||]b = null;|}")] [InlineData("{|result:string aa = null, bb = [||]null;|}")] [InlineData("{|result:string aa = null, bb = null[||];|}")] [InlineData("{|result:string aa = null, bb = null;[||]|}")] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestInHeader(string data) { var testText = @" class C { void M() { C LocalFunction(C c) { " + data + @"return null; } var a = new object(); } }"; await TestAsync<LocalDeclarationStatementSyntax>(testText); } #endregion #region TestHidden [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestNextToHidden() { var testText = @" #line default class C { void M() { #line hidden var a = b; #line default {|result:C [||]LocalFunction(C c) { return null; }|} } }"; await TestAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestNextToHidden2() { var testText = @" #line default class C { void M() { #line hidden var a = b; #line default {|result:C [||]LocalFunction(C c) { return null; }|} #line hidden var a = b; #line default } }"; await TestAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingHidden() { var testText = @" #line default class C { void M() { #line hidden C LocalFunction(C c) #line default { return null; }[||] } }"; await TestMissingAsync<LocalFunctionStatementSyntax>(testText); } #endregion #region Test predicate [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingPredicate() { var testText = @" class C { void M() { N([||]2+3); } void N(int a) { } }"; await TestMissingAsync<ArgumentSyntax>(testText, n => n.Parent is TupleExpressionSyntax); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestArgument() { var testText = @" class C { void M() { N({|result:[||]2+3|}); } void N(int a) { } }"; await TestAsync<ArgumentSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestPredicate() { var testText = @" class C { void M() { var a = ({|result:[||]2 + 3|}, 2 + 3); } }"; await TestAsync<ArgumentSyntax>(testText, n => n.Parent is TupleExpressionSyntax); } #endregion #region Test arguments [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestArgumentsExtractionsInInitializer() { var testText = @" using System; class C { class TestAttribute : Attribute { } public C({|result:[Test]int a = [||]42|}, int b = 41) {} }"; await TestAsync<ParameterSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingArgumentsExtractionsSelectInitializer() { var testText = @" using System; class C { class TestAttribute : Attribute { } public C([Test]int a = [|42|], int b = 41) {} }"; await TestMissingAsync<ParameterSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingArgumentsExtractionsSelectComma() { var testText = @" using System; class C { class TestAttribute : Attribute { } public C([Test]int a = 42[|,|] int b = 41) {} }"; await TestMissingAsync<ParameterSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingArgumentsExtractionsInAttributes() { var testText = @" using System; class C { class TestAttribute : Attribute { } public C([[||]Test]int a = 42, int b = 41) {} }"; await TestMissingAsync<ParameterSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingArgumentsExtractionsSelectType1() { var testText = @" using System; class C { class TestAttribute : Attribute { } public C([Test][|int|] a = 42, int b = 41) {} }"; await TestMissingAsync<ParameterSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingArgumentsExtractionsSelectType2() { var testText = @" using System; class C { class TestAttribute : Attribute { } public C([Test][|C|] a = null, int b = 41) {} }"; await TestMissingAsync<ParameterSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestArgumentsExtractionsAtTheEnd() { var testText = @" using System; class C { class TestAttribute : Attribute { } public C({|result:[Test]int a = 42[||]|}, int b = 41) {} }"; await TestAsync<ParameterSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestArgumentsExtractionsBefore() { var testText = @" using System; class C { class TestAttribute : Attribute { } public C([||]{|result:[Test]int a = 42|}, int b = 41) {} }"; await TestAsync<ParameterSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestArgumentsExtractionsSelectParamName() { var testText = @" using System; class C { class TestAttribute : Attribute { } public C({|result:[Test]int [|a|] = 42|}, int b = 41) {} }"; await TestAsync<ParameterSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestArgumentsExtractionsSelectParam1() { var testText = @" using System; class C { class TestAttribute : Attribute { } public C({|result:[Test][|int a|] = 42|}, int b = 41) {} }"; await TestAsync<ParameterSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestArgumentsExtractionsSelectParam2() { var testText = @" using System; class C { class TestAttribute : Attribute { } public C([|{|result:[Test]int a = 42|}|], int b = 41) {} }"; await TestAsync<ParameterSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestArgumentsExtractionsSelectParam3() { var testText = @" using System; class C { class TestAttribute : Attribute { } public C({|result:[Test][|int a = 42|]|}, int b = 41) {} }"; await TestAsync<ParameterSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestArgumentsExtractionsInHeader() { var testText = @" using System; class CC { class TestAttribute : Attribute { } public CC({|result:[Test]C[||]C a = 42|}, int b = 41) {} }"; await TestAsync<ParameterSyntax>(testText); } #endregion #region Test methods [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingMethodExplicitInterfaceSelection() { var testText = @" using System; class C { class TestAttribute : Attribute { } public void [|I|].A([Test]int a = 42, int b = 41) {} }"; await TestMissingAsync<MethodDeclarationSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMethodCaretBeforeInterfaceSelection() { var testText = @" using System; class C { class TestAttribute : Attribute { } {|result:public void [||]I.A([Test]int a = 42, int b = 41) {}|} }"; await TestAsync<MethodDeclarationSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMethodNameAndExplicitInterfaceSelection() { var testText = @" using System; class C { class TestAttribute : Attribute { } {|result:public void [|I.A|]([Test]int a = 42, int b = 41) {}|} }"; await TestAsync<MethodDeclarationSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMethodInHeader() { var testText = @" using System; class CC { class TestAttribute : Attribute { } {|result:public C[||]C I.A([Test]int a = 42, int b = 41) { return null; }|} }"; await TestAsync<MethodDeclarationSyntax>(testText); } #endregion #region TestLocalDeclaration [Theory] [InlineData("{|result:v[||]ar name = \"\";|}")] [InlineData("{|result:string name = \"\", b[||]b = null;|}")] [InlineData("{|result:var[||] name = \"\";|}")] [InlineData("{|result:var [||]name = \"\";|}")] [InlineData("{|result:var na[||]me = \"\";|}")] [InlineData("{|result:var name[||] = \"\";|}")] [InlineData("{|result:var name [||]= \"\";|}")] [InlineData("{|result:var name =[||] \"\";|}")] [InlineData("{|result:var name = [||]\"\";|}")] [InlineData("{|result:[|var name = \"\";|]|}")] [InlineData("{|result:var name = \"\"[||];|}")] [InlineData("{|result:var name = \"\";[||]|}")] [InlineData("{|result:var name = \"\"[||]|}")] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestLocalDeclarationInHeader(string data) { var testText = @" class C { void M() { C LocalFunction(C c) { " + data + @"return null; } var a = new object(); } }"; await TestAsync<LocalDeclarationStatementSyntax>(testText); } [Theory] [InlineData("var name = \"[||]\";")] [InlineData("var name=[|\"\"|];")] [InlineData("string name = \"\", bb = n[||]ull;")] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingLocalDeclarationCaretInHeader(string data) { var testText = @" class C { void M() { C LocalFunction(C c) { " + data + @"return null; } var a = new object(); } }"; await TestMissingAsync<LocalDeclarationStatementSyntax>(testText); } #endregion #region Test Ifs [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] [Fact] public async Task TestMultiline_IfElseIfElseSelection1() { await TestAsync<IfStatementSyntax>( @"class A { void Goo() { {|result:[|if (a) { a(); }|] else if (b) { b(); } else { c(); }|} } }"); } [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] [Fact] public async Task TestMultiline_IfElseIfElseSelection2() { await TestAsync<IfStatementSyntax>( @"class A { void Goo() { {|result:[|if (a) { a(); } else if (b) { b(); } else { c(); }|]|} } }"); } [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] [Fact] public async Task TestMissingMultiline_IfElseIfElseSelection() { await TestMissingAsync<IfStatementSyntax>( @"class A { void Goo() { if (a) { a(); } [|else if (b) { b(); } else { c(); }|] } }"); } #endregion #region Test Deep in expression [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestDeepIn() { var testText = @" class C { void M() { N({|result:2+[||]3+4|}); } void N(int a) { } }"; await TestAsync<ArgumentSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingDeepInSecondRow() { var testText = @" class C { void M() { N(2 +[||]3+4); } void N(int a) { } }"; await TestMissingAsync<ArgumentSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestDeepInExpression() { var testText = @" class C { void M() { var b = ({|result:N(2[||])|}, 0); } int N(int a) { return a; } }"; await TestAsync<ArgumentSyntax>(testText, predicate: n => n.Parent is TupleExpressionSyntax); } #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.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editor.UnitTests.RefactoringHelpers; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.RefactoringHelpers { public partial class RefactoringHelpersTests : RefactoringHelpersTestBase<CSharpTestWorkspaceFixture> { #region Locations [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestInTokenDirectlyUnderNode() { var testText = @" class C { void M() { {|result:C Local[||]Function(C c) { return null; }|} } }"; await TestAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestBeforeTokenDirectlyUnderNode() { var testText = @" class C { void M() { {|result:C [||]LocalFunction(C c) { return null; }|} } }"; await TestAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestAfterTokenDirectlyUnderNode() { var testText = @" class C { void M() { {|result:C [||]LocalFunction(C c) { return null; }|} } }"; await TestAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingInTokenUnderDifferentNode() { var testText = @" class C { void M() { C LocalFunction(C c) { [||]return null; } } }"; await TestMissingAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestClimbRightEdge() { var testText = @" class C { void M() { {|result:C LocalFunction(C c) { return null; }[||]|} } }"; await TestAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestClimbLeftEdge() { var testText = @" class C { void M() { {|result:[||]C LocalFunction(C c) { return null; }|} } }"; await TestAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestClimbLeftEdgeComments() { var testText = @" class C { void M() { /// <summary> /// Comment1 /// </summary> {|result:[||]C LocalFunction(C c) { return null; }|} } }"; await TestAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingInAnotherChildNode() { var testText = @" class C { void M() { C LocalFunction(C c) { [||]return null; } } }"; await TestMissingAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingInTooFarBeforeInWhitespace() { var testText = @" class C { void M() { [||] C LocalFunction(C c) { return null; } } }"; await TestMissingAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingInWhiteSpaceOnLineWithDifferentStatement() { var testText = @" class C { void M() { var a = null; [||] C LocalFunction(C c) { return null; } } }"; await TestMissingAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestNotBeforePrecedingComment() { var testText = @" class C { void M() { [||]//Test comment C LocalFunction(C c) { return null; } } }"; await TestMissingAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestBeforeInWhitespace1_OnSameLine() { var testText = @" class C { void M() { [||] {|result:C LocalFunction(C c) { return null; }|} } }"; await TestAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestBeforeInWhitespace1_OnPreviousLine() { var testText = @" class C { void M() { [||] {|result:C LocalFunction(C c) { return null; }|} } }"; await TestAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestBeforeInWhitespace1_NotOnMultipleLinesPrior() { var testText = @" class C { void M() { [||] C LocalFunction(C c) { return null; } } }"; await TestMissingAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestBeforeInWhitespace2() { var testText = @" class C { void M() { var a = null; [||] {|result:C LocalFunction(C c) { return null; }|} } }"; await TestAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingInNextTokensLeadingTrivia() { var testText = @" class C { void M() { C LocalFunction(C c) { return null; } [||] } }"; await TestMissingAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestInEmptySyntaxNode() { var testText = @" class C { void M() { N(0, N(0, [||]{|result:|}, 0)); } int N(int a, int b, int c) { } }"; await TestAsync<ArgumentSyntax>(testText); } #endregion #region Selections [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestSelectedTokenDirectlyUnderNode() { var testText = @" class C { void M() { {|result:C [|LocalFunction|](C c) { return null; }|} } }"; await TestAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestPartiallySelectedTokenDirectlyUnderNode() { var testText = @" class C { void M() { {|result:C Lo[|calFunct|]ion(C c) { return null; }|} } }"; await TestAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestSelectedMultipleTokensUnderNode() { var testText = @" class C { void M() { {|result:[|C LocalFunction(C c)|] { return null; }|} } }"; await TestAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingSelectedMultipleTokensWithLowerCommonAncestor() { var testText = @" class C { void M() { C LocalFunction(C c) [|{ return null; }|] } }"; await TestMissingAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingSelectedLowerNode() { var testText = @" class C { void M() { [|C|] LocalFunction(C c) { return null; } } }"; await TestMissingAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingSelectedWhitespace() { var testText = @" class C { void M() { C[| |]LocalFunction(C c) { return null; } } }"; await TestMissingAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingSelectedWhitespace2() { var testText = @" class C { void M() { [| |]C LocalFunction(C c) { return null; } } }"; await TestMissingAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestCompleteSelection() { var testText = @" class C { void M() { {|result:[|C LocalFunction(C c) { return null; }|]|} } }"; await TestAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestOverSelection() { var testText = @" class C { void M() { [| {|result:C LocalFunction(C c) { return null; }|} |]var a = new object(); } }"; await TestAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestOverSelectionComments() { var testText = @" class C { void M() { // Co[|mment1 {|result:C LocalFunction(C c) { return null; }|}|] } }"; await TestAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingOverSelection() { var testText = @" class C { void M() { [| C LocalFunction(C c) { return null; } v|]ar a = new object(); } }"; await TestMissingAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingSelectionBefore() { var testText = @" class C { void M() { [| |]C LocalFunction(C c) { return null; } var a = new object(); } }"; await TestMissingAsync<LocalFunctionStatementSyntax>(testText); } #endregion #region IsUnderselected [Fact] [WorkItem(38708, "https://github.com/dotnet/roslyn/issues/38708")] public async Task TestUnderselectionOnSemicolon() { var testText = @" class Program { static void Main() { {|result:Main()|}[|;|] } }"; await TestNotUnderselectedAsync<ExpressionSyntax>(testText); } [Fact] [WorkItem(38708, "https://github.com/dotnet/roslyn/issues/38708")] public async Task TestUnderselectionBug1() { var testText = @" class Program { public static void Method() { //[|> var str = {|result:"" <|] aaa""|}; } }"; await TestNotUnderselectedAsync<ExpressionSyntax>(testText); } [Fact] [WorkItem(38708, "https://github.com/dotnet/roslyn/issues/38708")] public async Task TestUnderselectionBug2() { var testText = @" class C { public void M() { Console.WriteLine(""Hello world"");[| {|result:Console.WriteLine(new |]C())|}; } }"; await TestNotUnderselectedAsync<ExpressionSyntax>(testText); } [Fact] [WorkItem(38708, "https://github.com/dotnet/roslyn/issues/38708")] public async Task TestUnderselection() { var testText = @" class C { public void M() { bool a = {|result:[|true || false || true|]|}; }"; await TestNotUnderselectedAsync<BinaryExpressionSyntax>(testText); } [Fact] [WorkItem(38708, "https://github.com/dotnet/roslyn/issues/38708")] public async Task TestUnderselection2() { var testText = @" class C { public void M() { bool a = true || [|false || true|] || true; }"; await TestUnderselectedAsync<BinaryExpressionSyntax>(testText); } #endregion #region Attributes [Fact] [WorkItem(37584, "https://github.com/dotnet/roslyn/issues/37584")] public async Task TestMissingEmptyMember() { var testText = @" using System; public class Class1 { [][||] }"; await TestMissingAsync<MethodDeclarationSyntax>(testText); } [Fact] [WorkItem(38502, "https://github.com/dotnet/roslyn/issues/38502")] public async Task TestIncompleteAttribute() { var testText = @" using System; public class Class1 { {|result:void foo([[||]bar) {}|} }"; await TestAsync<MethodDeclarationSyntax>(testText); } [Fact] [WorkItem(38502, "https://github.com/dotnet/roslyn/issues/38502")] public async Task TestIncompleteAttribute2() { var testText = @" using System; public class Class1 { {|result:void foo([[||]Class1 arg1) {}|} }"; await TestAsync<MethodDeclarationSyntax>(testText); } [Fact] [WorkItem(37837, "https://github.com/dotnet/roslyn/issues/37837")] public async Task TestEmptyParameter() { var testText = @" using System; public class TestAttribute : Attribute { } public class Class1 { static void foo({|result:[Test][||] |} { } }"; await TestAsync<ParameterSyntax>(testText); } [Fact] [WorkItem(37584, "https://github.com/dotnet/roslyn/issues/37584")] public async Task TestMissingEmptyMember2() { var testText = @" using System; public class Class1 { [||]// Comment [] }"; await TestMissingAsync<MethodDeclarationSyntax>(testText); } [Fact] [WorkItem(37584, "https://github.com/dotnet/roslyn/issues/37584")] public async Task TestEmptyAttributeList() { var testText = @" using System; public class Class1 { {|result:[] [||]void a() {}|} }"; await TestAsync<MethodDeclarationSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestClimbLeftEdgeBeforeAttribute() { var testText = @" using System; class C { class TestAttribute : Attribute { } // Comment1 [||]{|result:[Test] void M() { }|} }"; await TestAsync<MethodDeclarationSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestClimbLeftEdgeAfterAttribute() { var testText = @" using System; class C { class TestAttribute : Attribute { } {|result:[Test] [||]void M() { }|} }"; await TestAsync<MethodDeclarationSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestClimbLeftEdgeAfterAttributeComments() { var testText = @" using System; class C { class TestAttribute : Attribute { } // Comment1 {|result:[Test] // Comment2 [||]void M() { }|} }"; await TestAsync<MethodDeclarationSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestClimbLeftEdgeAfterAttributes() { var testText = @" using System; class C { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } // Comment1 {|result:[Test] [Test2] // Comment2 [||]void M() { }|} }"; await TestAsync<MethodDeclarationSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingBetweenAttributes() { var testText = @" using System; class C { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } [Test] [||][Test2] void M() { } }"; await TestMissingAsync<MethodDeclarationSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingBetweenInAttributes() { var testText = @" using System; class C { class TestAttribute : Attribute { } [[||]Test] void M() { } }"; await TestMissingAsync<MethodDeclarationSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingSelectedAttributes() { var testText = @" using System; class C { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } [|[Test] [Test2]|] void M() { } }"; await TestMissingAsync<MethodDeclarationSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingSelectedAttribute() { var testText = @" using System; class C { class TestAttribute : Attribute { } [|[Test]|] void M() { } }"; await TestMissingAsync<MethodDeclarationSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestSelectedWholeNodeAndAttributes() { var testText = @" using System; class C { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } // Comment1 [|{|result:[Test] [Test2] // Comment2 void M() { }|}|] }"; await TestAsync<MethodDeclarationSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestSelectedWholeNodeWithoutAttributes() { var testText = @" using System; class C { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } // Comment1 {|result:[Test] [Test2] // Comment2 [|void M() { }|]|} }"; await TestAsync<MethodDeclarationSyntax>(testText); } #endregion #region Extractions general [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestExtractionsClimbing() { var testText = @" using System; class C { void M() { var a = {|result:new object()|};[||] } }"; await TestAsync<ObjectCreationExpressionSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingExtractHeaderForSelection() { var testText = @" using System; class C { class TestAttribute : Attribute { } [Test] public [|int|] a { get; set; } }"; await TestMissingAsync<PropertyDeclarationSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMultipleExtractions() { var localDeclaration = "{|result:string name = \"\", b[||]b = null;|}"; var localDeclarator = "string name = \"\", {|result:bb[||] = null|};"; await TestAsync<LocalDeclarationStatementSyntax>(GetTestText(localDeclaration)); await TestAsync<VariableDeclaratorSyntax>(GetTestText(localDeclarator)); static string GetTestText(string data) { return @" class C { void M() { C LocalFunction(C c) { " + data + @"return null; } var a = new object(); } }"; } } #endregion #region Extractions [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestExtractFromDeclaration() { var testText = @" using System; class C { void M() { [|var a = {|result:new object()|};|] } }"; await TestAsync<ObjectCreationExpressionSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestExtractFromDeclaration2() { var testText = @" using System; class C { void M() { var a = [|{|result:new object()|};|] } }"; await TestAsync<ObjectCreationExpressionSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestExtractFromAssignment() { var testText = @" using System; class C { void M() { object a; a = [|{|result:new object()|};|] } }"; await TestAsync<ObjectCreationExpressionSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestExtractFromDeclarator() { var testText = @" using System; class C { void M() { var [|a = {|result:new object()|}|]; } }"; await TestAsync<ObjectCreationExpressionSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestExtractFromDeclarator2() { var testText = @" using System; class C { void M() { {|result:var [|a = new object()|];|} } }"; await TestAsync<LocalDeclarationStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestExtractInHeaderOfProperty() { var testText = @" using System; class C { class TestAttribute : Attribute { } {|result:[Test] public i[||]nt a { get; set; }|} }"; await TestAsync<PropertyDeclarationSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingExtractNotInHeaderOfProperty() { var testText = @" using System; class C { class TestAttribute : Attribute { } [Test] public int a { [||]get; set; } }"; await TestMissingAsync<PropertyDeclarationSyntax>(testText); } #endregion #region Headers & holes [Theory] [InlineData("var aa = nul[||]l;")] [InlineData("var aa = n[||]ull;")] [InlineData("string aa = null, bb = n[||]ull;")] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingInHeaderHole(string data) { var testText = @" class C { void M() { C LocalFunction(C c) { " + data + @"return null; } var a = new object(); } }"; await TestMissingAsync<LocalDeclarationStatementSyntax>(testText); } [Theory] [InlineData("{|result:[||]var aa = null;|}")] [InlineData("{|result:var aa = [||]null;|}")] [InlineData("{|result:var aa = null[||];|}")] [InlineData("{|result:string aa = null, b[||]b = null;|}")] [InlineData("{|result:string aa = null, bb = [||]null;|}")] [InlineData("{|result:string aa = null, bb = null[||];|}")] [InlineData("{|result:string aa = null, bb = null;[||]|}")] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestInHeader(string data) { var testText = @" class C { void M() { C LocalFunction(C c) { " + data + @"return null; } var a = new object(); } }"; await TestAsync<LocalDeclarationStatementSyntax>(testText); } #endregion #region TestHidden [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestNextToHidden() { var testText = @" #line default class C { void M() { #line hidden var a = b; #line default {|result:C [||]LocalFunction(C c) { return null; }|} } }"; await TestAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestNextToHidden2() { var testText = @" #line default class C { void M() { #line hidden var a = b; #line default {|result:C [||]LocalFunction(C c) { return null; }|} #line hidden var a = b; #line default } }"; await TestAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingHidden() { var testText = @" #line default class C { void M() { #line hidden C LocalFunction(C c) #line default { return null; }[||] } }"; await TestMissingAsync<LocalFunctionStatementSyntax>(testText); } #endregion #region Test predicate [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingPredicate() { var testText = @" class C { void M() { N([||]2+3); } void N(int a) { } }"; await TestMissingAsync<ArgumentSyntax>(testText, n => n.Parent is TupleExpressionSyntax); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestArgument() { var testText = @" class C { void M() { N({|result:[||]2+3|}); } void N(int a) { } }"; await TestAsync<ArgumentSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestPredicate() { var testText = @" class C { void M() { var a = ({|result:[||]2 + 3|}, 2 + 3); } }"; await TestAsync<ArgumentSyntax>(testText, n => n.Parent is TupleExpressionSyntax); } #endregion #region Test arguments [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestArgumentsExtractionsInInitializer() { var testText = @" using System; class C { class TestAttribute : Attribute { } public C({|result:[Test]int a = [||]42|}, int b = 41) {} }"; await TestAsync<ParameterSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingArgumentsExtractionsSelectInitializer() { var testText = @" using System; class C { class TestAttribute : Attribute { } public C([Test]int a = [|42|], int b = 41) {} }"; await TestMissingAsync<ParameterSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingArgumentsExtractionsSelectComma() { var testText = @" using System; class C { class TestAttribute : Attribute { } public C([Test]int a = 42[|,|] int b = 41) {} }"; await TestMissingAsync<ParameterSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingArgumentsExtractionsInAttributes() { var testText = @" using System; class C { class TestAttribute : Attribute { } public C([[||]Test]int a = 42, int b = 41) {} }"; await TestMissingAsync<ParameterSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingArgumentsExtractionsSelectType1() { var testText = @" using System; class C { class TestAttribute : Attribute { } public C([Test][|int|] a = 42, int b = 41) {} }"; await TestMissingAsync<ParameterSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingArgumentsExtractionsSelectType2() { var testText = @" using System; class C { class TestAttribute : Attribute { } public C([Test][|C|] a = null, int b = 41) {} }"; await TestMissingAsync<ParameterSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestArgumentsExtractionsAtTheEnd() { var testText = @" using System; class C { class TestAttribute : Attribute { } public C({|result:[Test]int a = 42[||]|}, int b = 41) {} }"; await TestAsync<ParameterSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestArgumentsExtractionsBefore() { var testText = @" using System; class C { class TestAttribute : Attribute { } public C([||]{|result:[Test]int a = 42|}, int b = 41) {} }"; await TestAsync<ParameterSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestArgumentsExtractionsSelectParamName() { var testText = @" using System; class C { class TestAttribute : Attribute { } public C({|result:[Test]int [|a|] = 42|}, int b = 41) {} }"; await TestAsync<ParameterSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestArgumentsExtractionsSelectParam1() { var testText = @" using System; class C { class TestAttribute : Attribute { } public C({|result:[Test][|int a|] = 42|}, int b = 41) {} }"; await TestAsync<ParameterSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestArgumentsExtractionsSelectParam2() { var testText = @" using System; class C { class TestAttribute : Attribute { } public C([|{|result:[Test]int a = 42|}|], int b = 41) {} }"; await TestAsync<ParameterSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestArgumentsExtractionsSelectParam3() { var testText = @" using System; class C { class TestAttribute : Attribute { } public C({|result:[Test][|int a = 42|]|}, int b = 41) {} }"; await TestAsync<ParameterSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestArgumentsExtractionsInHeader() { var testText = @" using System; class CC { class TestAttribute : Attribute { } public CC({|result:[Test]C[||]C a = 42|}, int b = 41) {} }"; await TestAsync<ParameterSyntax>(testText); } #endregion #region Test methods [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingMethodExplicitInterfaceSelection() { var testText = @" using System; class C { class TestAttribute : Attribute { } public void [|I|].A([Test]int a = 42, int b = 41) {} }"; await TestMissingAsync<MethodDeclarationSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMethodCaretBeforeInterfaceSelection() { var testText = @" using System; class C { class TestAttribute : Attribute { } {|result:public void [||]I.A([Test]int a = 42, int b = 41) {}|} }"; await TestAsync<MethodDeclarationSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMethodNameAndExplicitInterfaceSelection() { var testText = @" using System; class C { class TestAttribute : Attribute { } {|result:public void [|I.A|]([Test]int a = 42, int b = 41) {}|} }"; await TestAsync<MethodDeclarationSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMethodInHeader() { var testText = @" using System; class CC { class TestAttribute : Attribute { } {|result:public C[||]C I.A([Test]int a = 42, int b = 41) { return null; }|} }"; await TestAsync<MethodDeclarationSyntax>(testText); } #endregion #region TestLocalDeclaration [Theory] [InlineData("{|result:v[||]ar name = \"\";|}")] [InlineData("{|result:string name = \"\", b[||]b = null;|}")] [InlineData("{|result:var[||] name = \"\";|}")] [InlineData("{|result:var [||]name = \"\";|}")] [InlineData("{|result:var na[||]me = \"\";|}")] [InlineData("{|result:var name[||] = \"\";|}")] [InlineData("{|result:var name [||]= \"\";|}")] [InlineData("{|result:var name =[||] \"\";|}")] [InlineData("{|result:var name = [||]\"\";|}")] [InlineData("{|result:[|var name = \"\";|]|}")] [InlineData("{|result:var name = \"\"[||];|}")] [InlineData("{|result:var name = \"\";[||]|}")] [InlineData("{|result:var name = \"\"[||]|}")] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestLocalDeclarationInHeader(string data) { var testText = @" class C { void M() { C LocalFunction(C c) { " + data + @"return null; } var a = new object(); } }"; await TestAsync<LocalDeclarationStatementSyntax>(testText); } [Theory] [InlineData("var name = \"[||]\";")] [InlineData("var name=[|\"\"|];")] [InlineData("string name = \"\", bb = n[||]ull;")] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingLocalDeclarationCaretInHeader(string data) { var testText = @" class C { void M() { C LocalFunction(C c) { " + data + @"return null; } var a = new object(); } }"; await TestMissingAsync<LocalDeclarationStatementSyntax>(testText); } #endregion #region Test Ifs [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] [Fact] public async Task TestMultiline_IfElseIfElseSelection1() { await TestAsync<IfStatementSyntax>( @"class A { void Goo() { {|result:[|if (a) { a(); }|] else if (b) { b(); } else { c(); }|} } }"); } [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] [Fact] public async Task TestMultiline_IfElseIfElseSelection2() { await TestAsync<IfStatementSyntax>( @"class A { void Goo() { {|result:[|if (a) { a(); } else if (b) { b(); } else { c(); }|]|} } }"); } [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] [Fact] public async Task TestMissingMultiline_IfElseIfElseSelection() { await TestMissingAsync<IfStatementSyntax>( @"class A { void Goo() { if (a) { a(); } [|else if (b) { b(); } else { c(); }|] } }"); } #endregion #region Test Deep in expression [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestDeepIn() { var testText = @" class C { void M() { N({|result:2+[||]3+4|}); } void N(int a) { } }"; await TestAsync<ArgumentSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingDeepInSecondRow() { var testText = @" class C { void M() { N(2 +[||]3+4); } void N(int a) { } }"; await TestMissingAsync<ArgumentSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestDeepInExpression() { var testText = @" class C { void M() { var b = ({|result:N(2[||])|}, 0); } int N(int a) { return a; } }"; await TestAsync<ArgumentSyntax>(testText, predicate: n => n.Parent is TupleExpressionSyntax); } #endregion } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Rules/NextAlignTokensOperationAction.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Formatting.Rules { [NonDefaultable] internal readonly struct NextAlignTokensOperationAction { private readonly ImmutableArray<AbstractFormattingRule> _formattingRules; private readonly int _index; private readonly SyntaxNode _node; private readonly List<AlignTokensOperation> _list; public NextAlignTokensOperationAction( ImmutableArray<AbstractFormattingRule> formattingRules, int index, SyntaxNode node, List<AlignTokensOperation> list) { _formattingRules = formattingRules; _index = index; _node = node; _list = list; } private NextAlignTokensOperationAction NextAction => new(_formattingRules, _index + 1, _node, _list); public void Invoke() { // If we have no remaining handlers to execute, then we'll execute our last handler if (_index >= _formattingRules.Length) { return; } else { // Call the handler at the index, passing a continuation that will come back to here with index + 1 _formattingRules[_index].AddAlignTokensOperations(_list, _node, NextAction); return; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Formatting.Rules { [NonDefaultable] internal readonly struct NextAlignTokensOperationAction { private readonly ImmutableArray<AbstractFormattingRule> _formattingRules; private readonly int _index; private readonly SyntaxNode _node; private readonly List<AlignTokensOperation> _list; public NextAlignTokensOperationAction( ImmutableArray<AbstractFormattingRule> formattingRules, int index, SyntaxNode node, List<AlignTokensOperation> list) { _formattingRules = formattingRules; _index = index; _node = node; _list = list; } private NextAlignTokensOperationAction NextAction => new(_formattingRules, _index + 1, _node, _list); public void Invoke() { // If we have no remaining handlers to execute, then we'll execute our last handler if (_index >= _formattingRules.Length) { return; } else { // Call the handler at the index, passing a continuation that will come back to here with index + 1 _formattingRules[_index].AddAlignTokensOperations(_list, _node, NextAction); return; } } } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/Compilers/Test/Core/Assert/EqualityTesting.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Xunit; namespace Microsoft.CodeAnalysis.Test.Utilities { /// <summary> /// Helpers for testing equality APIs. /// Gives us more control than calling Assert.Equals. /// </summary> public static class EqualityTesting { public static void AssertEqual<T>(IEquatable<T> x, IEquatable<T> y) { Assert.True(x.Equals(y)); Assert.True(((object)x).Equals(y)); Assert.Equal(x.GetHashCode(), y.GetHashCode()); } public static void AssertNotEqual<T>(IEquatable<T> x, IEquatable<T> y) { Assert.False(x.Equals(y)); Assert.False(((object)x).Equals(y)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Xunit; namespace Microsoft.CodeAnalysis.Test.Utilities { /// <summary> /// Helpers for testing equality APIs. /// Gives us more control than calling Assert.Equals. /// </summary> public static class EqualityTesting { public static void AssertEqual<T>(IEquatable<T> x, IEquatable<T> y) { Assert.True(x.Equals(y)); Assert.True(((object)x).Equals(y)); Assert.Equal(x.GetHashCode(), y.GetHashCode()); } public static void AssertNotEqual<T>(IEquatable<T> x, IEquatable<T> y) { Assert.False(x.Equals(y)); Assert.False(((object)x).Equals(y)); } } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/Analyzers/CSharp/Tests/RemoveUnusedParametersAndValues/RemoveUnusedParametersTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.RemoveUnusedParametersAndValues; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; using static Roslyn.Test.Utilities.TestHelpers; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.RemoveUnusedParametersAndValues { public class RemoveUnusedParametersTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public RemoveUnusedParametersTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpRemoveUnusedParametersAndValuesDiagnosticAnalyzer(), new CSharpRemoveUnusedValuesCodeFixProvider()); private OptionsCollection NonPublicMethodsOnly => Option(CodeStyleOptions2.UnusedParameters, new CodeStyleOption2<UnusedParametersPreference>(UnusedParametersPreference.NonPublicMethods, NotificationOption2.Suggestion)); // Ensure that we explicitly test missing UnusedParameterDiagnosticId, which has no corresponding code fix (non-fixable diagnostic). private Task TestDiagnosticMissingAsync(string initialMarkup, ParseOptions parseOptions = null) => TestDiagnosticMissingAsync(initialMarkup, options: null, parseOptions); private Task TestDiagnosticsAsync(string initialMarkup, params DiagnosticDescription[] expectedDiagnostics) => TestDiagnosticsAsync(initialMarkup, options: null, parseOptions: null, expectedDiagnostics); private Task TestDiagnosticMissingAsync(string initialMarkup, OptionsCollection options, ParseOptions parseOptions = null) => TestDiagnosticMissingAsync(initialMarkup, new TestParameters(parseOptions, options: options, retainNonFixableDiagnostics: true)); private Task TestDiagnosticsAsync(string initialMarkup, OptionsCollection options, params DiagnosticDescription[] expectedDiagnostics) => TestDiagnosticsAsync(initialMarkup, options, parseOptions: null, expectedDiagnostics); private Task TestDiagnosticsAsync(string initialMarkup, OptionsCollection options, ParseOptions parseOptions, params DiagnosticDescription[] expectedDiagnostics) => TestDiagnosticsAsync(initialMarkup, new TestParameters(parseOptions, options: options, retainNonFixableDiagnostics: true), expectedDiagnostics); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task Parameter_Used() { await TestDiagnosticMissingAsync( @"class C { void M(int [|p|]) { var x = p; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task Parameter_Unused() { await TestDiagnosticsAsync( @"class C { void M(int [|p|]) { } }", Diagnostic(IDEDiagnosticIds.UnusedParameterDiagnosticId)); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] [InlineData("public", "public")] [InlineData("public", "protected")] public async Task Parameter_Unused_NonPrivate_NotApplicable(string typeAccessibility, string methodAccessibility) { await TestDiagnosticMissingAsync( $@"{typeAccessibility} class C {{ {methodAccessibility} void M(int [|p|]) {{ }} }}", NonPublicMethodsOnly); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] [InlineData("public", "private")] [InlineData("public", "internal")] [InlineData("internal", "private")] [InlineData("internal", "public")] [InlineData("internal", "internal")] [InlineData("internal", "protected")] public async Task Parameter_Unused_NonPublicMethod(string typeAccessibility, string methodAccessibility) { await TestDiagnosticsAsync( $@"{typeAccessibility} class C {{ {methodAccessibility} void M(int [|p|]) {{ }} }}", NonPublicMethodsOnly, Diagnostic(IDEDiagnosticIds.UnusedParameterDiagnosticId)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task Parameter_Unused_UnusedExpressionAssignment_PreferNone() { var unusedValueAssignmentOptionSuppressed = Option(CSharpCodeStyleOptions.UnusedValueAssignment, new CodeStyleOption2<UnusedValuePreference>(UnusedValuePreference.DiscardVariable, NotificationOption2.None)); await TestDiagnosticMissingAsync( @"class C { void M(int [|p|]) { var x = p; } }", options: unusedValueAssignmentOptionSuppressed); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task Parameter_WrittenOnly() { await TestDiagnosticsAsync( @"class C { void M(int [|p|]) { p = 1; } }", Diagnostic(IDEDiagnosticIds.UnusedParameterDiagnosticId)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task Parameter_WrittenThenRead() { await TestDiagnosticsAsync( @"class C { void M(int [|p|]) { p = 1; var x = p; } }", Diagnostic(IDEDiagnosticIds.UnusedParameterDiagnosticId)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task Parameter_WrittenOnAllControlPaths_BeforeRead() { await TestDiagnosticsAsync( @"class C { void M(int [|p|], bool flag) { if (flag) { p = 0; } else { p = 1; } var x = p; } }", Diagnostic(IDEDiagnosticIds.UnusedParameterDiagnosticId)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task Parameter_WrittenOnSomeControlPaths_BeforeRead() { await TestDiagnosticMissingAsync( @"class C { void M(int [|p|], bool flag, bool flag2) { if (flag) { if (flag2) { p = 0; } } else { p = 1; } var x = p; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task OptionalParameter_Unused() { await TestDiagnosticsAsync( @"class C { void M(int [|p|] = 0) { } }", Diagnostic(IDEDiagnosticIds.UnusedParameterDiagnosticId)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task Parameter_UsedInConstructorInitializerOnly() { await TestDiagnosticMissingAsync( @" class B { protected B(int p) { } } class C: B { C(int [|p|]) : base(p) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task Parameter_NotUsedInConstructorInitializer_UsedInConstructorBody() { await TestDiagnosticMissingAsync( @" class B { protected B(int p) { } } class C: B { C(int [|p|]) : base(0) { var x = p; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task Parameter_UsedInConstructorInitializerAndConstructorBody() { await TestDiagnosticMissingAsync( @" class B { protected B(int p) { } } class C: B { C(int [|p|]) : base(p) { var x = p; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task UnusedLocalFunctionParameter() { await TestDiagnosticsAsync( @"class C { void M(int y) { LocalFunction(y); void LocalFunction(int [|p|]) { } } }", Diagnostic(IDEDiagnosticIds.UnusedParameterDiagnosticId)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task UnusedLocalFunctionParameter_02() { await TestDiagnosticsAsync( @"class C { void M() { LocalFunction(0); void LocalFunction(int [|p|]) { } } }", Diagnostic(IDEDiagnosticIds.UnusedParameterDiagnosticId)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task UnusedLocalFunctionParameter_Discard() { await TestDiagnosticMissingAsync( @"class C { void M() { LocalFunction(0); void LocalFunction(int [|_|]) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task UnusedLocalFunctionParameter_PassedAsDelegateArgument() { await TestDiagnosticMissingAsync( @"using System; class C { void M() { M2(LocalFunction); void LocalFunction(int [|p|]) { } } void M2(Action<int> a) => a(0); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task UsedInLambda_ReturnsDelegate() { // Currently we bail out from analysis for method returning delegate types. await TestDiagnosticMissingAsync( @"using System; class C { private static Action<int> M(object [|p|] = null, Action<object> myDelegate) { return d => { myDelegate(p); }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task UnusedInLambda_ReturnsDelegate() { // We bail out from unused value analysis for method returning delegate types. // We should still report unused parameters. await TestDiagnosticsAsync( @"using System; class C { private static Action M(object [|p|]) { return () => { }; } }", Diagnostic(IDEDiagnosticIds.UnusedParameterDiagnosticId)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task UnusedInLambda_LambdaPassedAsArgument() { // We bail out from unused value analysis when lambda is passed as argument. // We should still report unused parameters. await TestDiagnosticsAsync( @"using System; class C { private static void M(object [|p|]) { M2(() => { }); } private static void M2(Action a) { } }", Diagnostic(IDEDiagnosticIds.UnusedParameterDiagnosticId)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task ReadInLambda_LambdaPassedAsArgument() { await TestDiagnosticMissingAsync( @"using System; class C { private static void M(object [|p|]) { M2(() => { M3(p); }); } private static void M2(Action a) { } private static void M3(object o) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task OnlyWrittenInLambda_LambdaPassedAsArgument() { await TestDiagnosticMissingAsync( @"using System; class C { private static void M(object [|p|]) { M2(() => { M3(out p); }); } private static void M2(Action a) { } private static void M3(out object o) { o = null; } }"); } [WorkItem(31744, "https://github.com/dotnet/roslyn/issues/31744")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task UnusedInExpressionTree_PassedAsArgument() { await TestDiagnosticsAsync( @"using System; using System.Linq.Expressions; class C { public static void M1(object [|p|]) { M2(x => x.M3()); } private static C M2(Expression<Func<C, int>> a) { return null; } private int M3() { return 0; } }", Diagnostic(IDEDiagnosticIds.UnusedParameterDiagnosticId)); } [WorkItem(31744, "https://github.com/dotnet/roslyn/issues/31744")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task ReadInExpressionTree_PassedAsArgument() { await TestDiagnosticMissingAsync( @"using System; using System.Linq.Expressions; class C { public static void M1(object [|p|]) { M2(x => x.M3(p)); } private static C M2(Expression<Func<C, int>> a) { return null; } private int M3(object o) { return 0; } }"); } [WorkItem(31744, "https://github.com/dotnet/roslyn/issues/31744")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task OnlyWrittenInExpressionTree_PassedAsArgument() { await TestDiagnosticMissingAsync( @"using System; using System.Linq.Expressions; class C { public static void M1(object [|p|]) { M2(x => x.M3(out p)); } private static C M2(Expression<Func<C, int>> a) { return null; } private int M3(out object o) { o = null; return 0; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task UsedInLambda_AssignedToField() { // Currently we bail out from analysis if we have a delegate creation that is not assigned // too a local/parameter. await TestDiagnosticMissingAsync( @"using System; class C { private Action _field; private static void M(object [|p|]) { _field = () => { Console.WriteLine(p); }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task MethodWithLockAndControlFlow() { await TestDiagnosticMissingAsync( @"using System; class C { private static readonly object s_gate = new object(); public static C M(object [|p|], bool flag, C c1, C c2) { C c; lock (s_gate) { c = flag > 0 ? c1 : c2; } c.M2(p); return c; } private void M2(object p) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task UnusedLambdaParameter() { await TestDiagnosticMissingAsync( @"using System; class C { void M(int y) { Action<int> myLambda = [|p|] => { }; myLambda(y); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task UnusedLambdaParameter_Discard() { await TestDiagnosticMissingAsync( @"using System; class C { void M(int y) { Action<int> myLambda = [|_|] => { }; myLambda(y); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task UnusedLambdaParameter_DiscardTwo() { await TestDiagnosticMissingAsync( @"using System; class C { void M(int y) { Action<int, int> myLambda = ([|_|], _) => { }; myLambda(y, y); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task UnusedLocalFunctionParameter_DiscardTwo() { await TestDiagnosticMissingAsync( @"using System; class C { void M(int y) { void local([|_|], _) { } local(y, y); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task UnusedMethodParameter_DiscardTwo() { await TestDiagnosticMissingAsync( @"using System; class C { void M([|_|], _) { } void M2(int y) { M(y, y); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task UsedLocalFunctionParameter() { await TestDiagnosticMissingAsync( @"class C { void M(int y) { LocalFunction(y); void LocalFunction(int [|p|]) { var x = p; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task UsedLambdaParameter() { await TestDiagnosticMissingAsync( @"using System; class C { void M(int y) { Action<int> myLambda = [|p|] => { var x = p; } myLambda(y); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task OptionalParameter_Used() { await TestDiagnosticMissingAsync( @"class C { void M(int [|p = 0|]) { var x = p; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task InParameter() { await TestDiagnosticsAsync( @"class C { void M(in int [|p|]) { } }", Diagnostic(IDEDiagnosticIds.UnusedParameterDiagnosticId)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task RefParameter_Unused() { await TestDiagnosticsAsync( @"class C { void M(ref int [|p|]) { } }", Diagnostic(IDEDiagnosticIds.UnusedParameterDiagnosticId)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task RefParameter_WrittenOnly() { await TestDiagnosticMissingAsync( @"class C { void M(ref int [|p|]) { p = 0; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task RefParameter_ReadOnly() { await TestDiagnosticMissingAsync( @"class C { void M(ref int [|p|]) { var x = p; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task RefParameter_ReadThenWritten() { await TestDiagnosticMissingAsync( @"class C { void M(ref int [|p|]) { var x = p; p = 1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task RefParameter_WrittenAndThenRead() { await TestDiagnosticMissingAsync( @"class C { void M(ref int [|p|]) { p = 1; var x = p; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task RefParameter_WrittenTwiceNotRead() { await TestDiagnosticMissingAsync( @"class C { void M(ref int [|p|]) { p = 0; p = 1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task OutParameter_Unused() { await TestDiagnosticsAsync( @"class C { void M(out int [|p|]) { } }", Diagnostic(IDEDiagnosticIds.UnusedParameterDiagnosticId)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task OutParameter_WrittenOnly() { await TestDiagnosticMissingAsync( @"class C { void M(out int [|p|]) { p = 0; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task OutParameter_WrittenAndThenRead() { await TestDiagnosticMissingAsync( @"class C { void M(out int [|p|]) { p = 0; var x = p; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task OutParameter_WrittenTwiceNotRead() { await TestDiagnosticMissingAsync( @"class C { void M(out int [|p|]) { p = 0; p = 1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task Parameter_ExternMethod() { await TestDiagnosticMissingAsync( @"class C { [System.Runtime.InteropServices.DllImport(nameof(M))] static extern void M(int [|p|]); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task Parameter_AbstractMethod() { await TestDiagnosticMissingAsync( @"abstract class C { protected abstract void M(int [|p|]); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task Parameter_VirtualMethod() { await TestDiagnosticMissingAsync( @"class C { protected virtual void M(int [|p|]) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task Parameter_OverriddenMethod() { await TestDiagnosticMissingAsync( @"class C { protected virtual void M(int p) { var x = p; } } class D : C { protected override void M(int [|p|]) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task Parameter_ImplicitInterfaceImplementationMethod() { await TestDiagnosticMissingAsync( @"interface I { void M(int p); } class C: I { public void M(int [|p|]) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task Parameter_ExplicitInterfaceImplementationMethod() { await TestDiagnosticMissingAsync( @"interface I { void M(int p); } class C: I { void I.M(int [|p|]) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task Parameter_IndexerMethod() { await TestDiagnosticMissingAsync( @"class C { int this[int [|p|]] { get { return 0; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task Parameter_ConditionalDirective() { await TestDiagnosticMissingAsync( @"class C { void M(int [|p|]) { #if DEBUG System.Console.WriteLine(p); #endif } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task Parameter_EventHandler_FirstParameter() { await TestDiagnosticMissingAsync( @"class C { public void MyHandler(object [|obj|], System.EventArgs args) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task Parameter_EventHandler_SecondParameter() { await TestDiagnosticMissingAsync( @"class C { public void MyHandler(object obj, System.EventArgs [|args|]) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task Parameter_MethodUsedAsEventHandler() { await TestDiagnosticMissingAsync( @"using System; public delegate void MyDelegate(int x); class C { private event MyDelegate myDel; void M(C c) { c.myDel += Handler; } void Handler(int [|x|]) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task Parameter_CustomEventArgs() { await TestDiagnosticMissingAsync( @"class C { public class CustomEventArgs : System.EventArgs { } public void MyHandler(object [|obj|], CustomEventArgs args) { } }"); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] [InlineData(@"[System.Diagnostics.Conditional(nameof(M))]")] [InlineData(@"[System.Obsolete]")] [InlineData(@"[System.Runtime.Serialization.OnDeserializingAttribute]")] [InlineData(@"[System.Runtime.Serialization.OnDeserializedAttribute]")] [InlineData(@"[System.Runtime.Serialization.OnSerializingAttribute]")] [InlineData(@"[System.Runtime.Serialization.OnSerializedAttribute]")] public async Task Parameter_MethodsWithSpecialAttributes(string attribute) { await TestDiagnosticMissingAsync( $@"class C {{ {attribute} void M(int [|p|]) {{ }} }}"); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] [InlineData("System.Composition", "ImportingConstructorAttribute")] [InlineData("System.ComponentModel.Composition", "ImportingConstructorAttribute")] public async Task Parameter_ConstructorsWithSpecialAttributes(string attributeNamespace, string attributeName) { await TestDiagnosticMissingAsync( $@" namespace {attributeNamespace} {{ public class {attributeName} : System.Attribute {{ }} }} class C {{ [{attributeNamespace}.{attributeName}()] public C(int [|p|]) {{ }} }}"); } [WorkItem(32133, "https://github.com/dotnet/roslyn/issues/32133")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task Parameter_SerializationConstructor() { await TestDiagnosticMissingAsync( @" using System; using System.Runtime.Serialization; internal sealed class NonSerializable { public NonSerializable(string value) => Value = value; public string Value { get; set; } } [Serializable] internal sealed class CustomSerializingType : ISerializable { private readonly NonSerializable _nonSerializable; public CustomSerializingType(SerializationInfo info, StreamingContext [|context|]) { _nonSerializable = new NonSerializable(info.GetString(""KEY"")); } public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue(""KEY"", _nonSerializable.Value); } }"); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task Parameter_DiagnosticMessages() { var source = @"public class C { // p1 is unused. // p2 is written before read. [|int M(int p1, int p2) { p2 = 0; return p2; } // p3 is unused parameter of a public API. // p4 is written before read parameter of a public API. public int M2(int p3, int p4) { p4 = 0; return p4; } void M3(int p5) { _ = nameof(p5); }|] }"; var testParameters = new TestParameters(retainNonFixableDiagnostics: true); using var workspace = CreateWorkspaceFromOptions(source, testParameters); var diagnostics = await GetDiagnosticsAsync(workspace, testParameters).ConfigureAwait(false); diagnostics.Verify( Diagnostic(IDEDiagnosticIds.UnusedParameterDiagnosticId, "p1").WithLocation(5, 15), Diagnostic(IDEDiagnosticIds.UnusedParameterDiagnosticId, "p2").WithLocation(5, 23), Diagnostic(IDEDiagnosticIds.UnusedParameterDiagnosticId, "p3").WithLocation(13, 23), Diagnostic(IDEDiagnosticIds.UnusedParameterDiagnosticId, "p4").WithLocation(13, 31), Diagnostic(IDEDiagnosticIds.UnusedParameterDiagnosticId, "p5").WithLocation(19, 17)); var sortedDiagnostics = diagnostics.OrderBy(d => d.Location.SourceSpan.Start).ToArray(); Assert.Equal("Remove unused parameter 'p1'", sortedDiagnostics[0].GetMessage()); Assert.Equal("Parameter 'p2' can be removed; its initial value is never used", sortedDiagnostics[1].GetMessage()); Assert.Equal("Remove unused parameter 'p3' if it is not part of a shipped public API", sortedDiagnostics[2].GetMessage()); Assert.Equal("Parameter 'p4' can be removed if it is not part of a shipped public API; its initial value is never used", sortedDiagnostics[3].GetMessage()); Assert.Equal("Parameter 'p5' can be removed; its initial value is never used", sortedDiagnostics[4].GetMessage()); } [WorkItem(32287, "https://github.com/dotnet/roslyn/issues/32287")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task Parameter_DeclarationPatternWithNullDeclaredSymbol() { await TestDiagnosticMissingAsync( @"class C { void M(object [|o|]) { if (o is int _) { } } }"); } [WorkItem(32851, "https://github.com/dotnet/roslyn/issues/32851")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task Parameter_Unused_SpecialNames() { await TestDiagnosticMissingAsync( @"class C { [|void M(int _, char _1, C _3)|] { } }"); } [WorkItem(32851, "https://github.com/dotnet/roslyn/issues/32851")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task Parameter_Used_SemanticError() { await TestDiagnosticMissingAsync( @"class C { void M(int [|x|]) { // CS1662: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type. Invoke<string>(() => x); T Invoke<T>(Func<T> a) { return a(); } } }"); } [WorkItem(32851, "https://github.com/dotnet/roslyn/issues/32851")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task Parameter_Unused_SemanticError() { await TestDiagnosticsAsync( @"class C { void M(int [|x|]) { // CS1662: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type. Invoke<string>(() => 0); T Invoke<T>(Func<T> a) { return a(); } } }", Diagnostic(IDEDiagnosticIds.UnusedParameterDiagnosticId)); } [WorkItem(32973, "https://github.com/dotnet/roslyn/issues/32973")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task OutParameter_LocalFunction() { await TestDiagnosticMissingAsync( @"class C { public static bool M(out int x) { return LocalFunction(out x); bool LocalFunction(out int [|y|]) { y = 0; return true; } } }"); } [WorkItem(32973, "https://github.com/dotnet/roslyn/issues/32973")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task RefParameter_Unused_LocalFunction() { await TestDiagnosticsAsync( @"class C { public static bool M(ref int x) { return LocalFunction(ref x); bool LocalFunction(ref int [|y|]) { return true; } } }", Diagnostic(IDEDiagnosticIds.UnusedParameterDiagnosticId)); } [WorkItem(32973, "https://github.com/dotnet/roslyn/issues/32973")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task RefParameter_Used_LocalFunction() { await TestDiagnosticMissingAsync( @"class C { public static bool M(ref int x) { return LocalFunction(ref x); bool LocalFunction(ref int [|y|]) { y = 0; return true; } } }"); } [WorkItem(33299, "https://github.com/dotnet/roslyn/issues/33299")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task NullCoalesceAssignment() { await TestDiagnosticMissingAsync( @"class C { public static void M(C [|x|]) { x ??= new C(); } }", parseOptions: new CSharpParseOptions(LanguageVersion.CSharp8)); } [WorkItem(34301, "https://github.com/dotnet/roslyn/issues/34301")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task GenericLocalFunction() { await TestDiagnosticsAsync( @"class C { void M() { LocalFunc(0); void LocalFunc<T>(T [|value|]) { } } }", Diagnostic(IDEDiagnosticIds.UnusedParameterDiagnosticId)); } [WorkItem(36715, "https://github.com/dotnet/roslyn/issues/36715")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task GenericLocalFunction_02() { await TestDiagnosticsAsync( @"using System.Collections.Generic; class C { void M(object [|value|]) { try { value = LocalFunc(0); } finally { value = LocalFunc(0); } return; IEnumerable<T> LocalFunc<T>(T value) { yield return value; } } }", Diagnostic(IDEDiagnosticIds.UnusedParameterDiagnosticId)); } [WorkItem(36715, "https://github.com/dotnet/roslyn/issues/36715")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task GenericLocalFunction_03() { await TestDiagnosticsAsync( @"using System; using System.Collections.Generic; class C { void M(object [|value|]) { Func<object, IEnumerable<object>> myDel = LocalFunc; try { value = myDel(value); } finally { value = myDel(value); } return; IEnumerable<T> LocalFunc<T>(T value) { yield return value; } } }"); } [WorkItem(34830, "https://github.com/dotnet/roslyn/issues/34830")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task RegressionTest_ShouldReportUnusedParameter() { var options = Option(CodeStyleOptions2.UnusedParameters, new CodeStyleOption2<UnusedParametersPreference>(default, NotificationOption2.Suggestion)); await TestDiagnosticMissingAsync( @"using System; using System.Threading.Tasks; public interface I { event Action MyAction; } public sealed class C : IDisposable { private readonly Task<I> task; public C(Task<I> [|task|]) { this.task = task; Task.Run(async () => (await task).MyAction += myAction); } private void myAction() { } public void Dispose() => task.Result.MyAction -= myAction; }", options); } #if !CODE_STYLE // Below test is not applicable for CodeStyle layer as attempting to fetch an editorconfig string representation for this invalid option fails. [WorkItem(37326, "https://github.com/dotnet/roslyn/issues/37326")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task RegressionTest_ShouldReportUnusedParameter_02() { var options = Option(CodeStyleOptions2.UnusedParameters, new CodeStyleOption2<UnusedParametersPreference>((UnusedParametersPreference)2, NotificationOption2.Suggestion)); await TestDiagnosticMissingAsync( @"using System; using System.Threading.Tasks; public interface I { event Action MyAction; } public sealed class C : IDisposable { private readonly Task<I> task; public C(Task<I> [|task|]) { this.task = task; Task.Run(async () => (await task).MyAction += myAction); } private void myAction() { } public void Dispose() => task.Result.MyAction -= myAction; }", options); } #endif [WorkItem(37483, "https://github.com/dotnet/roslyn/issues/37483")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task MethodUsedAsDelegateInGeneratedCode_NoDiagnostic() { await TestDiagnosticMissingAsync( @"using System; public partial class C { private void M(int [|x|]) { } } public partial class C { [System.CodeDom.Compiler.GeneratedCodeAttribute("""", """")] public void M2(out Action<int> a) { a = M; } } "); } [WorkItem(37483, "https://github.com/dotnet/roslyn/issues/37483")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task UnusedParameterInGeneratedCode_NoDiagnostic() { await TestDiagnosticMissingAsync( @"public partial class C { [System.CodeDom.Compiler.GeneratedCodeAttribute("""", """")] private void M(int [|x|]) { } } "); } [WorkItem(36817, "https://github.com/dotnet/roslyn/issues/36817")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task ParameterWithoutName_NoDiagnostic() { await TestDiagnosticMissingAsync( @"public class C { public void M[|(int )|] { } }"); } [WorkItem(41236, "https://github.com/dotnet/roslyn/issues/41236")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task NotImplementedException_NoDiagnostic1() { await TestDiagnosticMissingAsync( @"using System; class C { private void Goo(int [|i|]) { throw new NotImplementedException(); } }"); } [WorkItem(41236, "https://github.com/dotnet/roslyn/issues/41236")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task NotImplementedException_NoDiagnostic2() { await TestDiagnosticMissingAsync( @"using System; class C { private void Goo(int [|i|]) => throw new NotImplementedException(); }"); } [WorkItem(41236, "https://github.com/dotnet/roslyn/issues/41236")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task NotImplementedException_NoDiagnostic3() { await TestDiagnosticMissingAsync( @"using System; class C { public C(int [|i|]) => throw new NotImplementedException(); }"); } [WorkItem(41236, "https://github.com/dotnet/roslyn/issues/41236")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task NotImplementedException_MultipleStatements1() { await TestDiagnosticsAsync( @"using System; class C { private void Goo(int [|i|]) { throw new NotImplementedException(); return; } }", Diagnostic(IDEDiagnosticIds.UnusedParameterDiagnosticId)); } [WorkItem(41236, "https://github.com/dotnet/roslyn/issues/41236")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task NotImplementedException_MultipleStatements2() { await TestDiagnosticsAsync( @"using System; class C { private void Goo(int [|i|]) { if (true) throw new NotImplementedException(); } }", Diagnostic(IDEDiagnosticIds.UnusedParameterDiagnosticId)); } [WorkItem(47142, "https://github.com/dotnet/roslyn/issues/47142")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task Record_PrimaryConstructorParameter() { await TestMissingAsync( @"record A(int [|X|]);" ); } [WorkItem(47142, "https://github.com/dotnet/roslyn/issues/47142")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task Record_NonPrimaryConstructorParameter() { await TestDiagnosticsAsync( @"record A { public A(int [|X|]) { } } ", Diagnostic(IDEDiagnosticIds.UnusedParameterDiagnosticId)); } [WorkItem(47142, "https://github.com/dotnet/roslyn/issues/47142")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task Record_DelegatingPrimaryConstructorParameter() { await TestDiagnosticMissingAsync( @"record A(int X); record B(int X, int [|Y|]) : A(X); "); } [WorkItem(47174, "https://github.com/dotnet/roslyn/issues/47174")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task RecordPrimaryConstructorParameter_PublicRecord() { await TestDiagnosticMissingAsync( @"public record Base(int I) { } public record Derived(string [|S|]) : Base(42) { } "); } [WorkItem(45743, "https://github.com/dotnet/roslyn/issues/45743")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task RequiredGetInstanceMethodByICustomMarshaler() { await TestDiagnosticMissingAsync(@" using System; using System.Runtime.InteropServices; public class C : ICustomMarshaler { public void CleanUpManagedData(object ManagedObj) => throw new NotImplementedException(); public void CleanUpNativeData(IntPtr pNativeData) => throw new NotImplementedException(); public int GetNativeDataSize() => throw new NotImplementedException(); public IntPtr MarshalManagedToNative(object ManagedObj) => throw new NotImplementedException(); public object MarshalNativeToManaged(IntPtr pNativeData) => throw new NotImplementedException(); public static ICustomMarshaler GetInstance(string [|s|]) => 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.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.RemoveUnusedParametersAndValues; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; using static Roslyn.Test.Utilities.TestHelpers; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.RemoveUnusedParametersAndValues { public class RemoveUnusedParametersTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public RemoveUnusedParametersTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpRemoveUnusedParametersAndValuesDiagnosticAnalyzer(), new CSharpRemoveUnusedValuesCodeFixProvider()); private OptionsCollection NonPublicMethodsOnly => Option(CodeStyleOptions2.UnusedParameters, new CodeStyleOption2<UnusedParametersPreference>(UnusedParametersPreference.NonPublicMethods, NotificationOption2.Suggestion)); // Ensure that we explicitly test missing UnusedParameterDiagnosticId, which has no corresponding code fix (non-fixable diagnostic). private Task TestDiagnosticMissingAsync(string initialMarkup, ParseOptions parseOptions = null) => TestDiagnosticMissingAsync(initialMarkup, options: null, parseOptions); private Task TestDiagnosticsAsync(string initialMarkup, params DiagnosticDescription[] expectedDiagnostics) => TestDiagnosticsAsync(initialMarkup, options: null, parseOptions: null, expectedDiagnostics); private Task TestDiagnosticMissingAsync(string initialMarkup, OptionsCollection options, ParseOptions parseOptions = null) => TestDiagnosticMissingAsync(initialMarkup, new TestParameters(parseOptions, options: options, retainNonFixableDiagnostics: true)); private Task TestDiagnosticsAsync(string initialMarkup, OptionsCollection options, params DiagnosticDescription[] expectedDiagnostics) => TestDiagnosticsAsync(initialMarkup, options, parseOptions: null, expectedDiagnostics); private Task TestDiagnosticsAsync(string initialMarkup, OptionsCollection options, ParseOptions parseOptions, params DiagnosticDescription[] expectedDiagnostics) => TestDiagnosticsAsync(initialMarkup, new TestParameters(parseOptions, options: options, retainNonFixableDiagnostics: true), expectedDiagnostics); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task Parameter_Used() { await TestDiagnosticMissingAsync( @"class C { void M(int [|p|]) { var x = p; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task Parameter_Unused() { await TestDiagnosticsAsync( @"class C { void M(int [|p|]) { } }", Diagnostic(IDEDiagnosticIds.UnusedParameterDiagnosticId)); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] [InlineData("public", "public")] [InlineData("public", "protected")] public async Task Parameter_Unused_NonPrivate_NotApplicable(string typeAccessibility, string methodAccessibility) { await TestDiagnosticMissingAsync( $@"{typeAccessibility} class C {{ {methodAccessibility} void M(int [|p|]) {{ }} }}", NonPublicMethodsOnly); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] [InlineData("public", "private")] [InlineData("public", "internal")] [InlineData("internal", "private")] [InlineData("internal", "public")] [InlineData("internal", "internal")] [InlineData("internal", "protected")] public async Task Parameter_Unused_NonPublicMethod(string typeAccessibility, string methodAccessibility) { await TestDiagnosticsAsync( $@"{typeAccessibility} class C {{ {methodAccessibility} void M(int [|p|]) {{ }} }}", NonPublicMethodsOnly, Diagnostic(IDEDiagnosticIds.UnusedParameterDiagnosticId)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task Parameter_Unused_UnusedExpressionAssignment_PreferNone() { var unusedValueAssignmentOptionSuppressed = Option(CSharpCodeStyleOptions.UnusedValueAssignment, new CodeStyleOption2<UnusedValuePreference>(UnusedValuePreference.DiscardVariable, NotificationOption2.None)); await TestDiagnosticMissingAsync( @"class C { void M(int [|p|]) { var x = p; } }", options: unusedValueAssignmentOptionSuppressed); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task Parameter_WrittenOnly() { await TestDiagnosticsAsync( @"class C { void M(int [|p|]) { p = 1; } }", Diagnostic(IDEDiagnosticIds.UnusedParameterDiagnosticId)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task Parameter_WrittenThenRead() { await TestDiagnosticsAsync( @"class C { void M(int [|p|]) { p = 1; var x = p; } }", Diagnostic(IDEDiagnosticIds.UnusedParameterDiagnosticId)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task Parameter_WrittenOnAllControlPaths_BeforeRead() { await TestDiagnosticsAsync( @"class C { void M(int [|p|], bool flag) { if (flag) { p = 0; } else { p = 1; } var x = p; } }", Diagnostic(IDEDiagnosticIds.UnusedParameterDiagnosticId)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task Parameter_WrittenOnSomeControlPaths_BeforeRead() { await TestDiagnosticMissingAsync( @"class C { void M(int [|p|], bool flag, bool flag2) { if (flag) { if (flag2) { p = 0; } } else { p = 1; } var x = p; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task OptionalParameter_Unused() { await TestDiagnosticsAsync( @"class C { void M(int [|p|] = 0) { } }", Diagnostic(IDEDiagnosticIds.UnusedParameterDiagnosticId)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task Parameter_UsedInConstructorInitializerOnly() { await TestDiagnosticMissingAsync( @" class B { protected B(int p) { } } class C: B { C(int [|p|]) : base(p) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task Parameter_NotUsedInConstructorInitializer_UsedInConstructorBody() { await TestDiagnosticMissingAsync( @" class B { protected B(int p) { } } class C: B { C(int [|p|]) : base(0) { var x = p; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task Parameter_UsedInConstructorInitializerAndConstructorBody() { await TestDiagnosticMissingAsync( @" class B { protected B(int p) { } } class C: B { C(int [|p|]) : base(p) { var x = p; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task UnusedLocalFunctionParameter() { await TestDiagnosticsAsync( @"class C { void M(int y) { LocalFunction(y); void LocalFunction(int [|p|]) { } } }", Diagnostic(IDEDiagnosticIds.UnusedParameterDiagnosticId)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task UnusedLocalFunctionParameter_02() { await TestDiagnosticsAsync( @"class C { void M() { LocalFunction(0); void LocalFunction(int [|p|]) { } } }", Diagnostic(IDEDiagnosticIds.UnusedParameterDiagnosticId)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task UnusedLocalFunctionParameter_Discard() { await TestDiagnosticMissingAsync( @"class C { void M() { LocalFunction(0); void LocalFunction(int [|_|]) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task UnusedLocalFunctionParameter_PassedAsDelegateArgument() { await TestDiagnosticMissingAsync( @"using System; class C { void M() { M2(LocalFunction); void LocalFunction(int [|p|]) { } } void M2(Action<int> a) => a(0); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task UsedInLambda_ReturnsDelegate() { // Currently we bail out from analysis for method returning delegate types. await TestDiagnosticMissingAsync( @"using System; class C { private static Action<int> M(object [|p|] = null, Action<object> myDelegate) { return d => { myDelegate(p); }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task UnusedInLambda_ReturnsDelegate() { // We bail out from unused value analysis for method returning delegate types. // We should still report unused parameters. await TestDiagnosticsAsync( @"using System; class C { private static Action M(object [|p|]) { return () => { }; } }", Diagnostic(IDEDiagnosticIds.UnusedParameterDiagnosticId)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task UnusedInLambda_LambdaPassedAsArgument() { // We bail out from unused value analysis when lambda is passed as argument. // We should still report unused parameters. await TestDiagnosticsAsync( @"using System; class C { private static void M(object [|p|]) { M2(() => { }); } private static void M2(Action a) { } }", Diagnostic(IDEDiagnosticIds.UnusedParameterDiagnosticId)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task ReadInLambda_LambdaPassedAsArgument() { await TestDiagnosticMissingAsync( @"using System; class C { private static void M(object [|p|]) { M2(() => { M3(p); }); } private static void M2(Action a) { } private static void M3(object o) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task OnlyWrittenInLambda_LambdaPassedAsArgument() { await TestDiagnosticMissingAsync( @"using System; class C { private static void M(object [|p|]) { M2(() => { M3(out p); }); } private static void M2(Action a) { } private static void M3(out object o) { o = null; } }"); } [WorkItem(31744, "https://github.com/dotnet/roslyn/issues/31744")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task UnusedInExpressionTree_PassedAsArgument() { await TestDiagnosticsAsync( @"using System; using System.Linq.Expressions; class C { public static void M1(object [|p|]) { M2(x => x.M3()); } private static C M2(Expression<Func<C, int>> a) { return null; } private int M3() { return 0; } }", Diagnostic(IDEDiagnosticIds.UnusedParameterDiagnosticId)); } [WorkItem(31744, "https://github.com/dotnet/roslyn/issues/31744")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task ReadInExpressionTree_PassedAsArgument() { await TestDiagnosticMissingAsync( @"using System; using System.Linq.Expressions; class C { public static void M1(object [|p|]) { M2(x => x.M3(p)); } private static C M2(Expression<Func<C, int>> a) { return null; } private int M3(object o) { return 0; } }"); } [WorkItem(31744, "https://github.com/dotnet/roslyn/issues/31744")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task OnlyWrittenInExpressionTree_PassedAsArgument() { await TestDiagnosticMissingAsync( @"using System; using System.Linq.Expressions; class C { public static void M1(object [|p|]) { M2(x => x.M3(out p)); } private static C M2(Expression<Func<C, int>> a) { return null; } private int M3(out object o) { o = null; return 0; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task UsedInLambda_AssignedToField() { // Currently we bail out from analysis if we have a delegate creation that is not assigned // too a local/parameter. await TestDiagnosticMissingAsync( @"using System; class C { private Action _field; private static void M(object [|p|]) { _field = () => { Console.WriteLine(p); }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task MethodWithLockAndControlFlow() { await TestDiagnosticMissingAsync( @"using System; class C { private static readonly object s_gate = new object(); public static C M(object [|p|], bool flag, C c1, C c2) { C c; lock (s_gate) { c = flag > 0 ? c1 : c2; } c.M2(p); return c; } private void M2(object p) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task UnusedLambdaParameter() { await TestDiagnosticMissingAsync( @"using System; class C { void M(int y) { Action<int> myLambda = [|p|] => { }; myLambda(y); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task UnusedLambdaParameter_Discard() { await TestDiagnosticMissingAsync( @"using System; class C { void M(int y) { Action<int> myLambda = [|_|] => { }; myLambda(y); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task UnusedLambdaParameter_DiscardTwo() { await TestDiagnosticMissingAsync( @"using System; class C { void M(int y) { Action<int, int> myLambda = ([|_|], _) => { }; myLambda(y, y); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task UnusedLocalFunctionParameter_DiscardTwo() { await TestDiagnosticMissingAsync( @"using System; class C { void M(int y) { void local([|_|], _) { } local(y, y); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task UnusedMethodParameter_DiscardTwo() { await TestDiagnosticMissingAsync( @"using System; class C { void M([|_|], _) { } void M2(int y) { M(y, y); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task UsedLocalFunctionParameter() { await TestDiagnosticMissingAsync( @"class C { void M(int y) { LocalFunction(y); void LocalFunction(int [|p|]) { var x = p; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task UsedLambdaParameter() { await TestDiagnosticMissingAsync( @"using System; class C { void M(int y) { Action<int> myLambda = [|p|] => { var x = p; } myLambda(y); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task OptionalParameter_Used() { await TestDiagnosticMissingAsync( @"class C { void M(int [|p = 0|]) { var x = p; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task InParameter() { await TestDiagnosticsAsync( @"class C { void M(in int [|p|]) { } }", Diagnostic(IDEDiagnosticIds.UnusedParameterDiagnosticId)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task RefParameter_Unused() { await TestDiagnosticsAsync( @"class C { void M(ref int [|p|]) { } }", Diagnostic(IDEDiagnosticIds.UnusedParameterDiagnosticId)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task RefParameter_WrittenOnly() { await TestDiagnosticMissingAsync( @"class C { void M(ref int [|p|]) { p = 0; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task RefParameter_ReadOnly() { await TestDiagnosticMissingAsync( @"class C { void M(ref int [|p|]) { var x = p; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task RefParameter_ReadThenWritten() { await TestDiagnosticMissingAsync( @"class C { void M(ref int [|p|]) { var x = p; p = 1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task RefParameter_WrittenAndThenRead() { await TestDiagnosticMissingAsync( @"class C { void M(ref int [|p|]) { p = 1; var x = p; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task RefParameter_WrittenTwiceNotRead() { await TestDiagnosticMissingAsync( @"class C { void M(ref int [|p|]) { p = 0; p = 1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task OutParameter_Unused() { await TestDiagnosticsAsync( @"class C { void M(out int [|p|]) { } }", Diagnostic(IDEDiagnosticIds.UnusedParameterDiagnosticId)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task OutParameter_WrittenOnly() { await TestDiagnosticMissingAsync( @"class C { void M(out int [|p|]) { p = 0; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task OutParameter_WrittenAndThenRead() { await TestDiagnosticMissingAsync( @"class C { void M(out int [|p|]) { p = 0; var x = p; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task OutParameter_WrittenTwiceNotRead() { await TestDiagnosticMissingAsync( @"class C { void M(out int [|p|]) { p = 0; p = 1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task Parameter_ExternMethod() { await TestDiagnosticMissingAsync( @"class C { [System.Runtime.InteropServices.DllImport(nameof(M))] static extern void M(int [|p|]); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task Parameter_AbstractMethod() { await TestDiagnosticMissingAsync( @"abstract class C { protected abstract void M(int [|p|]); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task Parameter_VirtualMethod() { await TestDiagnosticMissingAsync( @"class C { protected virtual void M(int [|p|]) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task Parameter_OverriddenMethod() { await TestDiagnosticMissingAsync( @"class C { protected virtual void M(int p) { var x = p; } } class D : C { protected override void M(int [|p|]) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task Parameter_ImplicitInterfaceImplementationMethod() { await TestDiagnosticMissingAsync( @"interface I { void M(int p); } class C: I { public void M(int [|p|]) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task Parameter_ExplicitInterfaceImplementationMethod() { await TestDiagnosticMissingAsync( @"interface I { void M(int p); } class C: I { void I.M(int [|p|]) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task Parameter_IndexerMethod() { await TestDiagnosticMissingAsync( @"class C { int this[int [|p|]] { get { return 0; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task Parameter_ConditionalDirective() { await TestDiagnosticMissingAsync( @"class C { void M(int [|p|]) { #if DEBUG System.Console.WriteLine(p); #endif } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task Parameter_EventHandler_FirstParameter() { await TestDiagnosticMissingAsync( @"class C { public void MyHandler(object [|obj|], System.EventArgs args) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task Parameter_EventHandler_SecondParameter() { await TestDiagnosticMissingAsync( @"class C { public void MyHandler(object obj, System.EventArgs [|args|]) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task Parameter_MethodUsedAsEventHandler() { await TestDiagnosticMissingAsync( @"using System; public delegate void MyDelegate(int x); class C { private event MyDelegate myDel; void M(C c) { c.myDel += Handler; } void Handler(int [|x|]) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task Parameter_CustomEventArgs() { await TestDiagnosticMissingAsync( @"class C { public class CustomEventArgs : System.EventArgs { } public void MyHandler(object [|obj|], CustomEventArgs args) { } }"); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] [InlineData(@"[System.Diagnostics.Conditional(nameof(M))]")] [InlineData(@"[System.Obsolete]")] [InlineData(@"[System.Runtime.Serialization.OnDeserializingAttribute]")] [InlineData(@"[System.Runtime.Serialization.OnDeserializedAttribute]")] [InlineData(@"[System.Runtime.Serialization.OnSerializingAttribute]")] [InlineData(@"[System.Runtime.Serialization.OnSerializedAttribute]")] public async Task Parameter_MethodsWithSpecialAttributes(string attribute) { await TestDiagnosticMissingAsync( $@"class C {{ {attribute} void M(int [|p|]) {{ }} }}"); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] [InlineData("System.Composition", "ImportingConstructorAttribute")] [InlineData("System.ComponentModel.Composition", "ImportingConstructorAttribute")] public async Task Parameter_ConstructorsWithSpecialAttributes(string attributeNamespace, string attributeName) { await TestDiagnosticMissingAsync( $@" namespace {attributeNamespace} {{ public class {attributeName} : System.Attribute {{ }} }} class C {{ [{attributeNamespace}.{attributeName}()] public C(int [|p|]) {{ }} }}"); } [WorkItem(32133, "https://github.com/dotnet/roslyn/issues/32133")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task Parameter_SerializationConstructor() { await TestDiagnosticMissingAsync( @" using System; using System.Runtime.Serialization; internal sealed class NonSerializable { public NonSerializable(string value) => Value = value; public string Value { get; set; } } [Serializable] internal sealed class CustomSerializingType : ISerializable { private readonly NonSerializable _nonSerializable; public CustomSerializingType(SerializationInfo info, StreamingContext [|context|]) { _nonSerializable = new NonSerializable(info.GetString(""KEY"")); } public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue(""KEY"", _nonSerializable.Value); } }"); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task Parameter_DiagnosticMessages() { var source = @"public class C { // p1 is unused. // p2 is written before read. [|int M(int p1, int p2) { p2 = 0; return p2; } // p3 is unused parameter of a public API. // p4 is written before read parameter of a public API. public int M2(int p3, int p4) { p4 = 0; return p4; } void M3(int p5) { _ = nameof(p5); }|] }"; var testParameters = new TestParameters(retainNonFixableDiagnostics: true); using var workspace = CreateWorkspaceFromOptions(source, testParameters); var diagnostics = await GetDiagnosticsAsync(workspace, testParameters).ConfigureAwait(false); diagnostics.Verify( Diagnostic(IDEDiagnosticIds.UnusedParameterDiagnosticId, "p1").WithLocation(5, 15), Diagnostic(IDEDiagnosticIds.UnusedParameterDiagnosticId, "p2").WithLocation(5, 23), Diagnostic(IDEDiagnosticIds.UnusedParameterDiagnosticId, "p3").WithLocation(13, 23), Diagnostic(IDEDiagnosticIds.UnusedParameterDiagnosticId, "p4").WithLocation(13, 31), Diagnostic(IDEDiagnosticIds.UnusedParameterDiagnosticId, "p5").WithLocation(19, 17)); var sortedDiagnostics = diagnostics.OrderBy(d => d.Location.SourceSpan.Start).ToArray(); Assert.Equal("Remove unused parameter 'p1'", sortedDiagnostics[0].GetMessage()); Assert.Equal("Parameter 'p2' can be removed; its initial value is never used", sortedDiagnostics[1].GetMessage()); Assert.Equal("Remove unused parameter 'p3' if it is not part of a shipped public API", sortedDiagnostics[2].GetMessage()); Assert.Equal("Parameter 'p4' can be removed if it is not part of a shipped public API; its initial value is never used", sortedDiagnostics[3].GetMessage()); Assert.Equal("Parameter 'p5' can be removed; its initial value is never used", sortedDiagnostics[4].GetMessage()); } [WorkItem(32287, "https://github.com/dotnet/roslyn/issues/32287")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task Parameter_DeclarationPatternWithNullDeclaredSymbol() { await TestDiagnosticMissingAsync( @"class C { void M(object [|o|]) { if (o is int _) { } } }"); } [WorkItem(32851, "https://github.com/dotnet/roslyn/issues/32851")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task Parameter_Unused_SpecialNames() { await TestDiagnosticMissingAsync( @"class C { [|void M(int _, char _1, C _3)|] { } }"); } [WorkItem(32851, "https://github.com/dotnet/roslyn/issues/32851")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task Parameter_Used_SemanticError() { await TestDiagnosticMissingAsync( @"class C { void M(int [|x|]) { // CS1662: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type. Invoke<string>(() => x); T Invoke<T>(Func<T> a) { return a(); } } }"); } [WorkItem(32851, "https://github.com/dotnet/roslyn/issues/32851")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task Parameter_Unused_SemanticError() { await TestDiagnosticsAsync( @"class C { void M(int [|x|]) { // CS1662: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type. Invoke<string>(() => 0); T Invoke<T>(Func<T> a) { return a(); } } }", Diagnostic(IDEDiagnosticIds.UnusedParameterDiagnosticId)); } [WorkItem(32973, "https://github.com/dotnet/roslyn/issues/32973")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task OutParameter_LocalFunction() { await TestDiagnosticMissingAsync( @"class C { public static bool M(out int x) { return LocalFunction(out x); bool LocalFunction(out int [|y|]) { y = 0; return true; } } }"); } [WorkItem(32973, "https://github.com/dotnet/roslyn/issues/32973")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task RefParameter_Unused_LocalFunction() { await TestDiagnosticsAsync( @"class C { public static bool M(ref int x) { return LocalFunction(ref x); bool LocalFunction(ref int [|y|]) { return true; } } }", Diagnostic(IDEDiagnosticIds.UnusedParameterDiagnosticId)); } [WorkItem(32973, "https://github.com/dotnet/roslyn/issues/32973")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task RefParameter_Used_LocalFunction() { await TestDiagnosticMissingAsync( @"class C { public static bool M(ref int x) { return LocalFunction(ref x); bool LocalFunction(ref int [|y|]) { y = 0; return true; } } }"); } [WorkItem(33299, "https://github.com/dotnet/roslyn/issues/33299")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task NullCoalesceAssignment() { await TestDiagnosticMissingAsync( @"class C { public static void M(C [|x|]) { x ??= new C(); } }", parseOptions: new CSharpParseOptions(LanguageVersion.CSharp8)); } [WorkItem(34301, "https://github.com/dotnet/roslyn/issues/34301")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task GenericLocalFunction() { await TestDiagnosticsAsync( @"class C { void M() { LocalFunc(0); void LocalFunc<T>(T [|value|]) { } } }", Diagnostic(IDEDiagnosticIds.UnusedParameterDiagnosticId)); } [WorkItem(36715, "https://github.com/dotnet/roslyn/issues/36715")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task GenericLocalFunction_02() { await TestDiagnosticsAsync( @"using System.Collections.Generic; class C { void M(object [|value|]) { try { value = LocalFunc(0); } finally { value = LocalFunc(0); } return; IEnumerable<T> LocalFunc<T>(T value) { yield return value; } } }", Diagnostic(IDEDiagnosticIds.UnusedParameterDiagnosticId)); } [WorkItem(36715, "https://github.com/dotnet/roslyn/issues/36715")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task GenericLocalFunction_03() { await TestDiagnosticsAsync( @"using System; using System.Collections.Generic; class C { void M(object [|value|]) { Func<object, IEnumerable<object>> myDel = LocalFunc; try { value = myDel(value); } finally { value = myDel(value); } return; IEnumerable<T> LocalFunc<T>(T value) { yield return value; } } }"); } [WorkItem(34830, "https://github.com/dotnet/roslyn/issues/34830")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task RegressionTest_ShouldReportUnusedParameter() { var options = Option(CodeStyleOptions2.UnusedParameters, new CodeStyleOption2<UnusedParametersPreference>(default, NotificationOption2.Suggestion)); await TestDiagnosticMissingAsync( @"using System; using System.Threading.Tasks; public interface I { event Action MyAction; } public sealed class C : IDisposable { private readonly Task<I> task; public C(Task<I> [|task|]) { this.task = task; Task.Run(async () => (await task).MyAction += myAction); } private void myAction() { } public void Dispose() => task.Result.MyAction -= myAction; }", options); } #if !CODE_STYLE // Below test is not applicable for CodeStyle layer as attempting to fetch an editorconfig string representation for this invalid option fails. [WorkItem(37326, "https://github.com/dotnet/roslyn/issues/37326")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task RegressionTest_ShouldReportUnusedParameter_02() { var options = Option(CodeStyleOptions2.UnusedParameters, new CodeStyleOption2<UnusedParametersPreference>((UnusedParametersPreference)2, NotificationOption2.Suggestion)); await TestDiagnosticMissingAsync( @"using System; using System.Threading.Tasks; public interface I { event Action MyAction; } public sealed class C : IDisposable { private readonly Task<I> task; public C(Task<I> [|task|]) { this.task = task; Task.Run(async () => (await task).MyAction += myAction); } private void myAction() { } public void Dispose() => task.Result.MyAction -= myAction; }", options); } #endif [WorkItem(37483, "https://github.com/dotnet/roslyn/issues/37483")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task MethodUsedAsDelegateInGeneratedCode_NoDiagnostic() { await TestDiagnosticMissingAsync( @"using System; public partial class C { private void M(int [|x|]) { } } public partial class C { [System.CodeDom.Compiler.GeneratedCodeAttribute("""", """")] public void M2(out Action<int> a) { a = M; } } "); } [WorkItem(37483, "https://github.com/dotnet/roslyn/issues/37483")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task UnusedParameterInGeneratedCode_NoDiagnostic() { await TestDiagnosticMissingAsync( @"public partial class C { [System.CodeDom.Compiler.GeneratedCodeAttribute("""", """")] private void M(int [|x|]) { } } "); } [WorkItem(36817, "https://github.com/dotnet/roslyn/issues/36817")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task ParameterWithoutName_NoDiagnostic() { await TestDiagnosticMissingAsync( @"public class C { public void M[|(int )|] { } }"); } [WorkItem(41236, "https://github.com/dotnet/roslyn/issues/41236")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task NotImplementedException_NoDiagnostic1() { await TestDiagnosticMissingAsync( @"using System; class C { private void Goo(int [|i|]) { throw new NotImplementedException(); } }"); } [WorkItem(41236, "https://github.com/dotnet/roslyn/issues/41236")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task NotImplementedException_NoDiagnostic2() { await TestDiagnosticMissingAsync( @"using System; class C { private void Goo(int [|i|]) => throw new NotImplementedException(); }"); } [WorkItem(41236, "https://github.com/dotnet/roslyn/issues/41236")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task NotImplementedException_NoDiagnostic3() { await TestDiagnosticMissingAsync( @"using System; class C { public C(int [|i|]) => throw new NotImplementedException(); }"); } [WorkItem(41236, "https://github.com/dotnet/roslyn/issues/41236")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task NotImplementedException_MultipleStatements1() { await TestDiagnosticsAsync( @"using System; class C { private void Goo(int [|i|]) { throw new NotImplementedException(); return; } }", Diagnostic(IDEDiagnosticIds.UnusedParameterDiagnosticId)); } [WorkItem(41236, "https://github.com/dotnet/roslyn/issues/41236")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task NotImplementedException_MultipleStatements2() { await TestDiagnosticsAsync( @"using System; class C { private void Goo(int [|i|]) { if (true) throw new NotImplementedException(); } }", Diagnostic(IDEDiagnosticIds.UnusedParameterDiagnosticId)); } [WorkItem(47142, "https://github.com/dotnet/roslyn/issues/47142")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task Record_PrimaryConstructorParameter() { await TestMissingAsync( @"record A(int [|X|]);" ); } [WorkItem(47142, "https://github.com/dotnet/roslyn/issues/47142")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task Record_NonPrimaryConstructorParameter() { await TestDiagnosticsAsync( @"record A { public A(int [|X|]) { } } ", Diagnostic(IDEDiagnosticIds.UnusedParameterDiagnosticId)); } [WorkItem(47142, "https://github.com/dotnet/roslyn/issues/47142")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task Record_DelegatingPrimaryConstructorParameter() { await TestDiagnosticMissingAsync( @"record A(int X); record B(int X, int [|Y|]) : A(X); "); } [WorkItem(47174, "https://github.com/dotnet/roslyn/issues/47174")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task RecordPrimaryConstructorParameter_PublicRecord() { await TestDiagnosticMissingAsync( @"public record Base(int I) { } public record Derived(string [|S|]) : Base(42) { } "); } [WorkItem(45743, "https://github.com/dotnet/roslyn/issues/45743")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task RequiredGetInstanceMethodByICustomMarshaler() { await TestDiagnosticMissingAsync(@" using System; using System.Runtime.InteropServices; public class C : ICustomMarshaler { public void CleanUpManagedData(object ManagedObj) => throw new NotImplementedException(); public void CleanUpNativeData(IntPtr pNativeData) => throw new NotImplementedException(); public int GetNativeDataSize() => throw new NotImplementedException(); public IntPtr MarshalManagedToNative(object ManagedObj) => throw new NotImplementedException(); public object MarshalNativeToManaged(IntPtr pNativeData) => throw new NotImplementedException(); public static ICustomMarshaler GetInstance(string [|s|]) => null; } "); } } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/EditorFeatures/TestUtilities/Squiggles/SquiggleUtilities.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Implementation.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text.Tagging; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Squiggles { public static class SquiggleUtilities { // Squiggle tests require solution crawler to run. internal static TestComposition CompositionWithSolutionCrawler = EditorTestCompositions.EditorFeatures .RemoveParts(typeof(MockWorkspaceEventListenerProvider)); internal static async Task<(ImmutableArray<DiagnosticData>, ImmutableArray<ITagSpan<IErrorTag>>)> GetDiagnosticsAndErrorSpansAsync<TProvider>( TestWorkspace workspace, IReadOnlyDictionary<string, ImmutableArray<DiagnosticAnalyzer>> analyzerMap = null) where TProvider : AbstractDiagnosticsAdornmentTaggerProvider<IErrorTag> { using var wrapper = new DiagnosticTaggerWrapper<TProvider, IErrorTag>(workspace, analyzerMap); var tagger = wrapper.TaggerProvider.CreateTagger<IErrorTag>(workspace.Documents.First().GetTextBuffer()); using var disposable = tagger as IDisposable; await wrapper.WaitForTags(); var analyzerDiagnostics = await wrapper.AnalyzerService.GetDiagnosticsAsync(workspace.CurrentSolution); var snapshot = workspace.Documents.First().GetTextBuffer().CurrentSnapshot; var spans = tagger.GetTags(snapshot.GetSnapshotSpanCollection()).ToImmutableArray(); return (analyzerDiagnostics, spans); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Implementation.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text.Tagging; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Squiggles { public static class SquiggleUtilities { // Squiggle tests require solution crawler to run. internal static TestComposition CompositionWithSolutionCrawler = EditorTestCompositions.EditorFeatures .RemoveParts(typeof(MockWorkspaceEventListenerProvider)); internal static async Task<(ImmutableArray<DiagnosticData>, ImmutableArray<ITagSpan<IErrorTag>>)> GetDiagnosticsAndErrorSpansAsync<TProvider>( TestWorkspace workspace, IReadOnlyDictionary<string, ImmutableArray<DiagnosticAnalyzer>> analyzerMap = null) where TProvider : AbstractDiagnosticsAdornmentTaggerProvider<IErrorTag> { using var wrapper = new DiagnosticTaggerWrapper<TProvider, IErrorTag>(workspace, analyzerMap); var tagger = wrapper.TaggerProvider.CreateTagger<IErrorTag>(workspace.Documents.First().GetTextBuffer()); using var disposable = tagger as IDisposable; await wrapper.WaitForTags(); var analyzerDiagnostics = await wrapper.AnalyzerService.GetDiagnosticsAsync(workspace.CurrentSolution); var snapshot = workspace.Documents.First().GetTextBuffer().CurrentSnapshot; var spans = tagger.GetTags(snapshot.GetSnapshotSpanCollection()).ToImmutableArray(); return (analyzerDiagnostics, spans); } } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/Compilers/CSharp/Test/Semantic/Semantics/LocalFunctionTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using System; using System.Collections.Immutable; using System.Linq; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class LocalFunctionsTestBase : CSharpTestBase { internal static readonly CSharpParseOptions DefaultParseOptions = TestOptions.Regular; internal static void VerifyDiagnostics(string source, params DiagnosticDescription[] expected) { var comp = CreateCompilationWithMscorlib45AndCSharp(source, options: TestOptions.ReleaseDll, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics(expected); } } [CompilerTrait(CompilerFeature.LocalFunctions)] public class LocalFunctionTests : LocalFunctionsTestBase { [Fact, WorkItem(29656, "https://github.com/dotnet/roslyn/issues/29656")] public void RefReturningAsyncLocalFunction() { var source = @" public class C { async ref System.Threading.Tasks.Task M() { } public void M2() { _ = local(); async ref System.Threading.Tasks.Task local() { } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,11): error CS1073: Unexpected token 'ref' // async ref System.Threading.Tasks.Task M() { } Diagnostic(ErrorCode.ERR_UnexpectedToken, "ref").WithArguments("ref").WithLocation(4, 11), // (4,43): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread. // async ref System.Threading.Tasks.Task M() { } Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "M").WithLocation(4, 43), // (10,15): error CS1073: Unexpected token 'ref' // async ref System.Threading.Tasks.Task local() { } Diagnostic(ErrorCode.ERR_UnexpectedToken, "ref").WithArguments("ref").WithLocation(10, 15), // (10,47): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread. // async ref System.Threading.Tasks.Task local() { } Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "local").WithLocation(10, 47) ); } [ConditionalFact(typeof(DesktopOnly))] public void LocalFunctionResetsLockScopeFlag() { var source = @" using System; using System.Threading.Tasks; class C { static void Main() { lock (new Object()) { async Task localFunc() { Console.Write(""localFunc""); await Task.Yield(); } localFunc(); } } } "; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "localFunc"); } [ConditionalFact(typeof(DesktopOnly))] public void LocalFunctionResetsTryCatchFinallyScopeFlags() { var source = @" using System; using System.Collections.Generic; class C { static void Main() { try { IEnumerable<int> localFunc() { yield return 1; } foreach (int i in localFunc()) { Console.Write(i); } throw new Exception(); } catch (Exception) { IEnumerable<int> localFunc() { yield return 2; } foreach (int i in localFunc()) { Console.Write(i); } } finally { IEnumerable<int> localFunc() { yield return 3; } foreach (int i in localFunc()) { Console.Write(i); } } } } "; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "123"); } [ConditionalFact(typeof(DesktopOnly))] public void LocalFunctionDoesNotOverwriteInnerLockScopeFlag() { var source = @" using System; using System.Collections.Generic; using System.Threading.Tasks; class C { void M(List<Task> listOfTasks) { lock (new Object()) { async Task localFunc() { lock (new Object()) { await Task.Yield(); } } listOfTasks.Add(localFunc()); } } } "; var comp = CreateCompilationWithMscorlib46(source); comp.VerifyDiagnostics( // (16,21): error CS1996: Cannot await in the body of a lock statement // await Task.Yield(); Diagnostic(ErrorCode.ERR_BadAwaitInLock, "await Task.Yield()").WithLocation(16, 21)); } [ConditionalFact(typeof(DesktopOnly))] public void LocalFunctionDoesNotOverwriteInnerTryCatchFinallyScopeFlags() { var source = @" using System; using System.Collections.Generic; class C { void M() { try { IEnumerable<int> localFunc() { try { yield return 1; } catch (Exception) {} } localFunc(); } catch (Exception) { IEnumerable<int> localFunc() { try {} catch (Exception) { yield return 2; } } localFunc(); } finally { IEnumerable<int> localFunc() { try {} finally { yield return 3; } } localFunc(); } } } "; var comp = CreateCompilationWithMscorlib46(source); comp.VerifyDiagnostics( // (15,21): error CS1626: Cannot yield a value in the body of a try block with a catch clause // yield return 1; Diagnostic(ErrorCode.ERR_BadYieldInTryOfCatch, "yield").WithLocation(15, 21), // (29,21): error CS1631: Cannot yield a value in the body of a catch clause // yield return 2; Diagnostic(ErrorCode.ERR_BadYieldInCatch, "yield").WithLocation(29, 21), // (42,21): error CS1625: Cannot yield in the body of a finally clause // yield return 3; Diagnostic(ErrorCode.ERR_BadYieldInFinally, "yield").WithLocation(42, 21)); } [ConditionalFact(typeof(DesktopOnly))] public void RethrowingExceptionsInCatchInsideLocalFuncIsAllowed() { var source = @" using System; class C { static void Main() { try { throw new Exception(); } catch (Exception) { void localFunc() { try { throw new Exception(); } catch (Exception) { Console.Write(""localFunc""); throw; } } try { localFunc(); } catch (Exception) { Console.Write(""_thrown""); } } } } "; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "localFunc_thrown"); } [ConditionalFact(typeof(DesktopOnly))] public void RethrowingExceptionsInLocalFuncInsideCatchIsNotAllowed() { var source = @" using System; class C { static void Main() { try {} catch (Exception) { void localFunc() { throw; } localFunc(); } } } "; var comp = CreateCompilationWithMscorlib46(source); comp.VerifyDiagnostics( // (13,17): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause // throw; Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw").WithLocation(13, 17)); } [Fact] public void LocalFunctionTypeParametersUseCorrectBinder() { var text = @" class C { static void M() { void local<[X]T>() {} } }"; var tree = SyntaxFactory.ParseSyntaxTree(text, options: TestOptions.Regular9); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree, ignoreAccessibility: true); var newTree = SyntaxFactory.ParseSyntaxTree(text + " "); var m = newTree.GetRoot() .DescendantNodes().OfType<MethodDeclarationSyntax>().Single(); Assert.True(model.TryGetSpeculativeSemanticModelForMethodBody(m.Body.SpanStart, m, out model)); var x = newTree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Single(); Assert.Equal("X", x.Identifier.Text); // If we aren't using the right binder here, the compiler crashes going through the binder factory var info = model.GetSymbolInfo(x); Assert.Null(info.Symbol); comp.VerifyDiagnostics( // (6,21): error CS0246: The type or namespace name 'XAttribute' could not be found (are you missing a using directive or an assembly reference?) // void local<[X]T>() {} Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "X").WithArguments("XAttribute").WithLocation(6, 21), // (6,21): error CS0246: The type or namespace name 'X' could not be found (are you missing a using directive or an assembly reference?) // void local<[X]T>() {} Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "X").WithArguments("X").WithLocation(6, 21), // (6,14): warning CS8321: The local function 'local' is declared but never used // void local<[X]T>() {} Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local").WithArguments("local").WithLocation(6, 14)); } [Theory] [InlineData("[A] void local() { }")] [InlineData("[return: A] void local() { }")] [InlineData("void local([A] int i) { }")] [InlineData("void local<[A]T>() {}")] [InlineData("[A] int x = 123;")] public void LocalFunctionAttribute_SpeculativeSemanticModel(string statement) { string text = $@" using System; class A : Attribute {{}} class C {{ static void M() {{ {statement} }} }}"; var tree = SyntaxFactory.ParseSyntaxTree(text); var comp = (Compilation)CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var a = tree.GetRoot().DescendantNodes() .OfType<IdentifierNameSyntax>().ElementAt(2); Assert.Equal("A", a.Identifier.Text); var attrInfo = model.GetSymbolInfo(a); var attrType = comp.GlobalNamespace.GetTypeMember("A"); var attrCtor = attrType.GetMember(".ctor"); Assert.Equal(attrCtor, attrInfo.Symbol); // Assert that this is also true for the speculative semantic model var newTree = SyntaxFactory.ParseSyntaxTree(text + " "); var m = newTree.GetRoot() .DescendantNodes().OfType<MethodDeclarationSyntax>().Single(); Assert.True(model.TryGetSpeculativeSemanticModelForMethodBody(m.Body.SpanStart, m, out model)); a = newTree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().ElementAt(2); Assert.Equal("A", a.Identifier.Text); // If we aren't using the right binder here, the compiler crashes going through the binder factory var info = model.GetSymbolInfo(a); // This behavior is wrong. See https://github.com/dotnet/roslyn/issues/24135 Assert.Equal(attrType, info.Symbol); } [Theory] [InlineData(@"[Attr(42, Name = ""hello"")] void local() { }")] [InlineData(@"[return: Attr(42, Name = ""hello"")] void local() { }")] [InlineData(@"void local([Attr(42, Name = ""hello"")] int i) { }")] [InlineData(@"void local<[Attr(42, Name = ""hello"")]T>() {}")] [InlineData(@"[Attr(42, Name = ""hello"")] int x = 123;")] public void LocalFunctionAttribute_Argument_SemanticModel(string statement) { var text = $@" class Attr {{ public Attr(int id) {{ }} public string Name {{ get; set; }} }} class C {{ static void M() {{ {statement} }} }}"; var tree = SyntaxFactory.ParseSyntaxTree(text, options: TestOptions.Regular9); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree, ignoreAccessibility: true); validate(model, tree); var newTree = SyntaxFactory.ParseSyntaxTree(text + " ", options: TestOptions.Regular9); var mMethod = (MethodDeclarationSyntax)newTree.FindNodeOrTokenByKind(SyntaxKind.MethodDeclaration, occurrence: 1).AsNode(); Assert.True(model.TryGetSpeculativeSemanticModelForMethodBody(mMethod.Body.SpanStart, mMethod, out var newModel)); validate(newModel, newTree); static void validate(SemanticModel model, SyntaxTree tree) { var attributeSyntax = tree.GetRoot().DescendantNodes().OfType<AttributeSyntax>().Single(); var attrArgs = attributeSyntax.ArgumentList.Arguments; var attrArg0 = attrArgs[0].Expression; Assert.Null(model.GetSymbolInfo(attrArg0).Symbol); var argType0 = model.GetTypeInfo(attrArg0).Type; Assert.Equal(SpecialType.System_Int32, argType0.SpecialType); var attrArg1 = attrArgs[1].Expression; Assert.Null(model.GetSymbolInfo(attrArg1).Symbol); var argType1 = model.GetTypeInfo(attrArg1).Type; Assert.Equal(SpecialType.System_String, argType1.SpecialType); } } [Fact] public void LocalFunctionAttribute_OnFunction() { const string text = @" using System; class A : Attribute { } class C { void M() { [A] void local() { } } } "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (10,14): warning CS8321: The local function 'local' is declared but never used // void local() { } Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local").WithArguments("local").WithLocation(10, 14)); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var localFunction = tree.GetRoot().DescendantNodes() .OfType<LocalFunctionStatementSyntax>() .Single(); var attributeList = localFunction.AttributeLists.Single(); Assert.Null(attributeList.Target); var attribute = attributeList.Attributes.Single(); Assert.Equal("A", ((SimpleNameSyntax)attribute.Name).Identifier.ValueText); var symbol = (IMethodSymbol)model.GetDeclaredSymbol(localFunction); Assert.NotNull(symbol); var attributes = symbol.GetAttributes().As<CSharpAttributeData>(); Assert.Equal(new[] { "A" }, GetAttributeNames(attributes)); var returnAttributes = symbol.GetReturnTypeAttributes(); Assert.Empty(returnAttributes); } [Fact] public void LocalFunctionAttribute_OnFunction_Argument() { const string text = @" using System; class A : Attribute { internal A(int i) { } } class C { void M() { [A(42)] void local() { } } } "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (13,14): warning CS8321: The local function 'local' is declared but never used // void local() { } Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local").WithArguments("local").WithLocation(13, 14)); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var localFunction = tree.GetRoot().DescendantNodes() .OfType<LocalFunctionStatementSyntax>() .Single(); var attributeList = localFunction.AttributeLists.Single(); Assert.Null(attributeList.Target); var attribute = attributeList.Attributes.Single(); Assert.Equal("A", ((SimpleNameSyntax)attribute.Name).Identifier.ValueText); var symbol = (IMethodSymbol)model.GetDeclaredSymbol(localFunction); Assert.NotNull(symbol); var attributes = symbol.GetAttributes(); var attributeData = attributes.Single(); var aAttribute = comp.GetTypeByMetadataName("A"); Assert.Equal(aAttribute, attributeData.AttributeClass.GetSymbol()); Assert.Equal(aAttribute.InstanceConstructors.Single(), attributeData.AttributeConstructor.GetSymbol()); Assert.Equal(42, attributeData.ConstructorArguments.Single().Value); var returnAttributes = symbol.GetReturnTypeAttributes(); Assert.Empty(returnAttributes); } [Fact] public void LocalFunctionAttribute_OnFunction_LocalArgument() { const string text = @" using System; class A : Attribute { internal A(string s) { } } class C { void M() { #pragma warning disable 0219 // Unreferenced local variable string s1 = ""hello""; const string s2 = ""world""; #pragma warning disable 8321 // Unreferenced local function [A(s1)] // 1 void local1() { } [A(nameof(s1))] void local2() { } [A(s2)] void local3() { } [A(s1.ToString())] // 2 void local4() { } static string local5() => ""hello""; [A(local5())] // 3 void local6() { } } } "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (17,12): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(s1)] // 1 Diagnostic(ErrorCode.ERR_BadAttributeArgument, "s1").WithLocation(17, 12), // (26,12): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(s1.ToString())] // 2 Diagnostic(ErrorCode.ERR_BadAttributeArgument, "s1.ToString()").WithLocation(26, 12), // (31,12): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(local5())] // 3 Diagnostic(ErrorCode.ERR_BadAttributeArgument, "local5()").WithLocation(31, 12)); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var arg1 = (AttributeArgumentSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.AttributeArgument, occurrence: 1).AsNode(); Assert.Equal("System.String s1", model.GetSymbolInfo(arg1.Expression).Symbol.ToTestDisplayString()); Assert.Equal(SpecialType.System_String, model.GetTypeInfo(arg1.Expression).Type.SpecialType); var arg2 = (AttributeArgumentSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.AttributeArgument, occurrence: 2).AsNode(); Assert.Null(model.GetSymbolInfo(arg2.Expression).Symbol); Assert.Equal(SpecialType.System_String, model.GetTypeInfo(arg2.Expression).Type.SpecialType); var arg3 = (AttributeArgumentSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.AttributeArgument, occurrence: 3).AsNode(); Assert.Equal("System.String s2", model.GetSymbolInfo(arg3.Expression).Symbol.ToTestDisplayString()); Assert.Equal(SpecialType.System_String, model.GetTypeInfo(arg3.Expression).Type.SpecialType); } [Fact] public void LocalFunctionAttribute_OnFunction_DeclarationPattern() { const string text = @" using System; class A : Attribute { internal A(bool b) { } } class C { void M() { #pragma warning disable 8321 // Unreferenced local function [A(42 is int i)] // 1 void local1() { _ = i.ToString(); // 2 } _ = i.ToString(); // 3 } } "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (13,12): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(42 is int i)] // 1 Diagnostic(ErrorCode.ERR_BadAttributeArgument, "42 is int i").WithLocation(13, 12), // (16,17): error CS0103: The name 'i' does not exist in the current context // _ = i.ToString(); // 2 Diagnostic(ErrorCode.ERR_NameNotInContext, "i").WithArguments("i").WithLocation(16, 17), // (19,13): error CS0103: The name 'i' does not exist in the current context // _ = i.ToString(); // 3 Diagnostic(ErrorCode.ERR_NameNotInContext, "i").WithArguments("i").WithLocation(19, 13)); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var arg = (AttributeArgumentSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.AttributeArgument, occurrence: 1).AsNode(); Assert.Null(model.GetSymbolInfo(arg.Expression).Symbol); Assert.Equal(SpecialType.System_Boolean, model.GetTypeInfo(arg.Expression).Type.SpecialType); var decl = (DeclarationPatternSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.DeclarationPattern, occurrence: 1).AsNode(); Assert.Equal("System.Int32 i", model.GetDeclaredSymbol(decl.Designation).ToTestDisplayString()); } [Fact] public void LocalFunctionAttribute_OnFunction_OutVarInCall() { const string text = @" using System; class A : Attribute { internal A(bool b) { } } class C { void M1() { #pragma warning disable 8321 // Unreferenced local function [A(M2(out var i))] // 1 void local1() { _ = i.ToString(); // 2 } _ = i.ToString(); // 3 } static bool M2(out int x) { x = 0; return false; } } "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (13,12): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(M2(out var i))] // 1 Diagnostic(ErrorCode.ERR_BadAttributeArgument, "M2(out var i)").WithLocation(13, 12), // (16,17): error CS0103: The name 'i' does not exist in the current context // _ = i.ToString(); // 2 Diagnostic(ErrorCode.ERR_NameNotInContext, "i").WithArguments("i").WithLocation(16, 17), // (19,13): error CS0103: The name 'i' does not exist in the current context // _ = i.ToString(); // 3 Diagnostic(ErrorCode.ERR_NameNotInContext, "i").WithArguments("i").WithLocation(19, 13)); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var arg = (AttributeArgumentSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.AttributeArgument, occurrence: 1).AsNode(); Assert.Equal("System.Boolean C.M2(out System.Int32 x)", model.GetSymbolInfo(arg.Expression).Symbol.ToTestDisplayString()); Assert.Equal(SpecialType.System_Boolean, model.GetTypeInfo(arg.Expression).Type.SpecialType); var decl = (DeclarationExpressionSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.DeclarationExpression, occurrence: 1).AsNode(); Assert.Equal("System.Int32 i", model.GetDeclaredSymbol(decl.Designation).ToTestDisplayString()); } [Fact] public void LocalFunctionAttribute_OutParam() { const string text = @" using System; class A : Attribute { internal A(out string s) { s = ""a""; } } class C { void M() { #pragma warning disable 8321, 0168 // Unreferenced local string s; [A(out s)] void local1() { } [A(out var s)] void local2() { } } } "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (15,12): error CS1041: Identifier expected; 'out' is a keyword // [A(out s)] Diagnostic(ErrorCode.ERR_IdentifierExpectedKW, "out").WithArguments("", "out").WithLocation(15, 12), // (15,16): error CS1620: Argument 1 must be passed with the 'out' keyword // [A(out s)] Diagnostic(ErrorCode.ERR_BadArgRef, "s").WithArguments("1", "out").WithLocation(15, 16), // (18,10): error CS1729: 'A' does not contain a constructor that takes 2 arguments // [A(out var s)] Diagnostic(ErrorCode.ERR_BadCtorArgCount, "A(out var s)").WithArguments("A", "2").WithLocation(18, 10), // (18,12): error CS1041: Identifier expected; 'out' is a keyword // [A(out var s)] Diagnostic(ErrorCode.ERR_IdentifierExpectedKW, "out").WithArguments("", "out").WithLocation(18, 12), // (18,16): error CS0103: The name 'var' does not exist in the current context // [A(out var s)] Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(18, 16), // (18,20): error CS1003: Syntax error, ',' expected // [A(out var s)] Diagnostic(ErrorCode.ERR_SyntaxError, "s").WithArguments(",", "").WithLocation(18, 20)); } [Fact] public void LocalFunctionAttribute_Return() { const string text = @" using System; class A : Attribute { } class C { void M() { [return: A] int local() => 42; } } "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (10,13): warning CS8321: The local function 'local' is declared but never used // int local() => 42; Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local").WithArguments("local").WithLocation(10, 13)); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var localFunction = tree.GetRoot().DescendantNodes() .OfType<LocalFunctionStatementSyntax>() .Single(); var attributeList = localFunction.AttributeLists.Single(); Assert.Equal(SyntaxKind.ReturnKeyword, attributeList.Target.Identifier.Kind()); var attribute = attributeList.Attributes.Single(); Assert.Equal("A", ((SimpleNameSyntax)attribute.Name).Identifier.ValueText); var symbol = (IMethodSymbol)model.GetDeclaredSymbol(localFunction); Assert.NotNull(symbol); var returnAttributes = symbol.GetReturnTypeAttributes(); var attributeData = returnAttributes.Single(); var aAttribute = comp.GetTypeByMetadataName("A"); Assert.Equal(aAttribute, attributeData.AttributeClass.GetSymbol()); Assert.Equal(aAttribute.InstanceConstructors.Single(), attributeData.AttributeConstructor.GetSymbol()); var attributes = symbol.GetAttributes(); Assert.Empty(attributes); } [Fact] public void LocalFunctionAttribute_Parameter() { var source = @" using System; class A : Attribute { } class C { void M() { int local([A] int i) => i; } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,13): warning CS8321: The local function 'local' is declared but never used // int local([A] int i) => i; Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local").WithArguments("local").WithLocation(9, 13)); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var localFunction = tree.GetRoot().DescendantNodes().OfType<LocalFunctionStatementSyntax>().Single(); var parameter = localFunction.ParameterList.Parameters.Single(); var paramSymbol = model.GetDeclaredSymbol(parameter); var attrs = paramSymbol.GetAttributes(); var attr = attrs.Single(); Assert.Equal(comp.GetTypeByMetadataName("A"), attr.AttributeClass.GetSymbol()); } [Fact] public void LocalFunctionAttribute_LangVersionError() { const string text = @" using System; class A : Attribute { } class C { void M() { #pragma warning disable 8321 // Unreferenced local function [A] void local1() { } [return: A] void local2() { } void local3([A] int i) { } void local4<[A] T>() { } } } "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (10,9): error CS8400: Feature 'local function attributes' is not available in C# 8.0. Please use language version 9.0 or greater. // [A] Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "[A]").WithArguments("local function attributes", "9.0").WithLocation(10, 9), // (13,9): error CS8400: Feature 'local function attributes' is not available in C# 8.0. Please use language version 9.0 or greater. // [return: A] Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "[return: A]").WithArguments("local function attributes", "9.0").WithLocation(13, 9), // (16,21): error CS8400: Feature 'local function attributes' is not available in C# 8.0. Please use language version 9.0 or greater. // void local3([A] int i) { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "[A]").WithArguments("local function attributes", "9.0").WithLocation(16, 21), // (18,21): error CS8400: Feature 'local function attributes' is not available in C# 8.0. Please use language version 9.0 or greater. // void local4<[A] T>() { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "[A]").WithArguments("local function attributes", "9.0").WithLocation(18, 21)); comp = CreateCompilation(text, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); } [Fact] public void LocalFunctionAttribute_BadAttributeLocation() { const string text = @" using System; [AttributeUsage(AttributeTargets.Property)] class PropAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method)] class MethodAttribute : Attribute { } [AttributeUsage(AttributeTargets.ReturnValue)] class ReturnAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter)] class ParamAttribute : Attribute { } [AttributeUsage(AttributeTargets.GenericParameter)] class TypeParamAttribute : Attribute { } public class C { public void M() { #pragma warning disable 8321 // Unreferenced local function [Prop] // 1 [Return] // 2 [Method] [return: Prop] // 3 [return: Return] [return: Method] // 4 void local< [Param] // 5 [TypeParam] T>( [Param] [TypeParam] // 6 T t) { } } } "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (22,10): error CS0592: Attribute 'Prop' is not valid on this declaration type. It is only valid on 'property, indexer' declarations. // [Prop] // 1 Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "Prop").WithArguments("Prop", "property, indexer").WithLocation(22, 10), // (23,10): error CS0592: Attribute 'Return' is not valid on this declaration type. It is only valid on 'return' declarations. // [Return] // 2 Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "Return").WithArguments("Return", "return").WithLocation(23, 10), // (25,18): error CS0592: Attribute 'Prop' is not valid on this declaration type. It is only valid on 'property, indexer' declarations. // [return: Prop] // 3 Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "Prop").WithArguments("Prop", "property, indexer").WithLocation(25, 18), // (27,18): error CS0592: Attribute 'Method' is not valid on this declaration type. It is only valid on 'method' declarations. // [return: Method] // 4 Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "Method").WithArguments("Method", "method").WithLocation(27, 18), // (29,14): error CS0592: Attribute 'Param' is not valid on this declaration type. It is only valid on 'parameter' declarations. // [Param] // 5 Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "Param").WithArguments("Param", "parameter").WithLocation(29, 14), // (33,14): error CS0592: Attribute 'TypeParam' is not valid on this declaration type. It is only valid on 'type parameter' declarations. // [TypeParam] // 6 Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "TypeParam").WithArguments("TypeParam", "type parameter").WithLocation(33, 14)); var tree = comp.SyntaxTrees.Single(); var localFunction = tree.GetRoot().DescendantNodes().OfType<LocalFunctionStatementSyntax>().Single(); var model = comp.GetSemanticModel(tree); var symbol = (IMethodSymbol)model.GetDeclaredSymbol(localFunction); Assert.NotNull(symbol); var attributes = symbol.GetAttributes(); Assert.Equal(3, attributes.Length); Assert.Equal(comp.GetTypeByMetadataName("PropAttribute"), attributes[0].AttributeClass.GetSymbol()); Assert.Equal(comp.GetTypeByMetadataName("ReturnAttribute"), attributes[1].AttributeClass.GetSymbol()); Assert.Equal(comp.GetTypeByMetadataName("MethodAttribute"), attributes[2].AttributeClass.GetSymbol()); var returnAttributes = symbol.GetReturnTypeAttributes(); Assert.Equal(3, returnAttributes.Length); Assert.Equal(comp.GetTypeByMetadataName("PropAttribute"), returnAttributes[0].AttributeClass.GetSymbol()); Assert.Equal(comp.GetTypeByMetadataName("ReturnAttribute"), returnAttributes[1].AttributeClass.GetSymbol()); Assert.Equal(comp.GetTypeByMetadataName("MethodAttribute"), returnAttributes[2].AttributeClass.GetSymbol()); } [Fact] public void LocalFunctionAttribute_AttributeSemanticModel() { const string text = @" using System; class A : Attribute { } class C { void M() { local1(); local2(); local3(0); local4<object>(); [A] void local1() { } [return: A] void local2() { } void local3([A] int i) { } void local4<[A] T>() { } } } "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var attributeSyntaxes = tree.GetRoot().DescendantNodes().OfType<AttributeSyntax>().ToList(); Assert.Equal(4, attributeSyntaxes.Count); var attributeConstructor = comp.GetTypeByMetadataName("A").InstanceConstructors.Single(); foreach (var attributeSyntax in attributeSyntaxes) { var symbol = model.GetSymbolInfo(attributeSyntax).Symbol.GetSymbol<MethodSymbol>(); Assert.Equal(attributeConstructor, symbol); } } [Fact] public void StatementAttributeSemanticModel() { const string text = @" using System; class A : Attribute { } class C { void M() { #pragma warning disable 219 // The variable '{0}' is assigned but its value is never used [A] int i = 0; } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (11,9): error CS7014: Attributes are not valid in this context. // [A] int i = 0; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(11, 9)); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var attrSyntax = tree.GetRoot().DescendantNodes().OfType<AttributeSyntax>().Single(); var attrConstructor = (IMethodSymbol)model.GetSymbolInfo(attrSyntax).Symbol; Assert.Equal(MethodKind.Constructor, attrConstructor.MethodKind); Assert.Equal("A", attrConstructor.ContainingType.Name); } [Fact] public void LocalFunctionNoBody() { const string text = @" class C { void M() { local1(); void local1(); } } "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,14): error CS8112: Local function 'local1()' must either have a body or be marked 'static extern'. // void local1(); Diagnostic(ErrorCode.ERR_LocalFunctionMissingBody, "local1").WithArguments("local1()").WithLocation(8, 14)); } [Fact] public void LocalFunctionExtern() { const string text = @" using System.Runtime.InteropServices; class C { void M() { #pragma warning disable 8321 // Unreferenced local function [DllImport(""a"")] extern void local1(); // 1, 2 [DllImport(""a"")] extern void local2() { } // 3, 4 [DllImport(""a"")] extern int local3() => 0; // 5, 6 static void local4(); // 7 static void local5() { } static int local6() => 0; [DllImport(""a"")] static extern void local7(); [DllImport(""a"")] static extern void local8() { } // 8 [DllImport(""a"")] static extern int local9() => 0; // 9 [DllImport(""a"")] extern static void local10(); [DllImport(""a"")] extern static void local11() { } // 10 [DllImport(""a"")] extern static int local12() => 0; // 11 } } "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (10,10): error CS0601: The DllImport attribute must be specified on a method marked 'static' and 'extern' // [DllImport("a")] extern void local1(); // 1, 2 Diagnostic(ErrorCode.ERR_DllImportOnInvalidMethod, "DllImport").WithLocation(10, 10), // (10,38): error CS8112: Local function 'local1()' must either have a body or be marked 'static extern'. // [DllImport("a")] extern void local1(); // 1, 2 Diagnostic(ErrorCode.ERR_LocalFunctionMissingBody, "local1").WithArguments("local1()").WithLocation(10, 38), // (11,10): error CS0601: The DllImport attribute must be specified on a method marked 'static' and 'extern' // [DllImport("a")] extern void local2() { } // 3, 4 Diagnostic(ErrorCode.ERR_DllImportOnInvalidMethod, "DllImport").WithLocation(11, 10), // (11,38): error CS0179: 'local2()' cannot be extern and declare a body // [DllImport("a")] extern void local2() { } // 3, 4 Diagnostic(ErrorCode.ERR_ExternHasBody, "local2").WithArguments("local2()").WithLocation(11, 38), // (12,10): error CS0601: The DllImport attribute must be specified on a method marked 'static' and 'extern' // [DllImport("a")] extern int local3() => 0; // 5, 6 Diagnostic(ErrorCode.ERR_DllImportOnInvalidMethod, "DllImport").WithLocation(12, 10), // (12,37): error CS0179: 'local3()' cannot be extern and declare a body // [DllImport("a")] extern int local3() => 0; // 5, 6 Diagnostic(ErrorCode.ERR_ExternHasBody, "local3").WithArguments("local3()").WithLocation(12, 37), // (14,21): error CS8112: Local function 'local4()' must either have a body or be marked 'static extern'. // static void local4(); // 7 Diagnostic(ErrorCode.ERR_LocalFunctionMissingBody, "local4").WithArguments("local4()").WithLocation(14, 21), // (19,45): error CS0179: 'local8()' cannot be extern and declare a body // [DllImport("a")] static extern void local8() { } // 8 Diagnostic(ErrorCode.ERR_ExternHasBody, "local8").WithArguments("local8()").WithLocation(19, 45), // (20,44): error CS0179: 'local9()' cannot be extern and declare a body // [DllImport("a")] static extern int local9() => 0; // 9 Diagnostic(ErrorCode.ERR_ExternHasBody, "local9").WithArguments("local9()").WithLocation(20, 44), // (23,45): error CS0179: 'local11()' cannot be extern and declare a body // [DllImport("a")] extern static void local11() { } // 10 Diagnostic(ErrorCode.ERR_ExternHasBody, "local11").WithArguments("local11()").WithLocation(23, 45), // (24,44): error CS0179: 'local12()' cannot be extern and declare a body // [DllImport("a")] extern static int local12() => 0; // 11 Diagnostic(ErrorCode.ERR_ExternHasBody, "local12").WithArguments("local12()").WithLocation(24, 44)); } [Fact] public void LocalFunctionExtern_Generic() { var source = @" using System; using System.Runtime.InteropServices; class C { #pragma warning disable 8321 // Unreferenced local function void M() { [DllImport(""a"")] extern static void local1(); [DllImport(""a"")] extern static void local2<T>(); // 1 void local3() { [DllImport(""a"")] extern static void local1(); [DllImport(""a"")] extern static void local2<T2>(); // 2 } void local4<T4>() { [DllImport(""a"")] extern static void local1(); // 3 [DllImport(""a"")] extern static void local2<T2>(); // 4 } Action a = () => { [DllImport(""a"")] extern static void local1(); [DllImport(""a"")] extern static void local2<T>(); // 5 void local3() { [DllImport(""a"")] extern static void local1(); [DllImport(""a"")] extern static void local2<T2>(); // 6 } void local4<T4>() { [DllImport(""a"")] extern static void local1(); // 7 [DllImport(""a"")] extern static void local2<T2>(); // 8 } }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (12,10): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type. // [DllImport("a")] extern static void local2<T>(); // 1 Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(12, 10), // (17,14): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type. // [DllImport("a")] extern static void local2<T2>(); // 2 Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(17, 14), // (22,14): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type. // [DllImport("a")] extern static void local1(); // 3 Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(22, 14), // (23,14): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type. // [DllImport("a")] extern static void local2<T2>(); // 4 Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(23, 14), // (29,14): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type. // [DllImport("a")] extern static void local2<T>(); // 5 Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(29, 14), // (34,18): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type. // [DllImport("a")] extern static void local2<T2>(); // 6 Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(34, 18), // (39,18): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type. // [DllImport("a")] extern static void local1(); // 7 Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(39, 18), // (40,18): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type. // [DllImport("a")] extern static void local2<T2>(); // 8 Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(40, 18)); } [Theory] [InlineData("<CT>", "", "")] [InlineData("", "<MT>", "")] [InlineData("", "", "<LT>")] public void LocalFunctionExtern_Generic_GenericMembers(string classTypeParams, string methodTypeParams, string localFunctionTypeParams) { var source = $@" using System; using System.Runtime.InteropServices; class C{classTypeParams} {{ #pragma warning disable 8321 // Unreferenced local function void M{methodTypeParams}() {{ void localOuter{localFunctionTypeParams}() {{ [DllImport(""a"")] extern static void local1(); // 1 [DllImport(""a"")] extern static void local2<T>(); // 2 void local3() {{ [DllImport(""a"")] extern static void local1(); // 3 [DllImport(""a"")] extern static void local2<T2>(); // 4 }} void local4<T4>() {{ [DllImport(""a"")] extern static void local1(); // 5 [DllImport(""a"")] extern static void local2<T2>(); // 6 }} Action a = () => {{ [DllImport(""a"")] extern static void local1(); // 7 [DllImport(""a"")] extern static void local2<T>(); // 8 void local3() {{ [DllImport(""a"")] extern static void local1(); // 9 [DllImport(""a"")] extern static void local2<T2>(); // 10 }} void local4<T4>() {{ [DllImport(""a"")] extern static void local1(); // 11 [DllImport(""a"")] extern static void local2<T2>(); // 12 }} }}; }} }} }}"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (13,14): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type. // [DllImport("a")] extern static void local1(); // 1 Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(13, 14), // (14,14): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type. // [DllImport("a")] extern static void local2<T>(); // 2 Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(14, 14), // (18,18): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type. // [DllImport("a")] extern static void local1(); // 3 Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(18, 18), // (19,18): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type. // [DllImport("a")] extern static void local2<T2>(); // 4 Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(19, 18), // (24,18): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type. // [DllImport("a")] extern static void local1(); // 5 Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(24, 18), // (25,18): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type. // [DllImport("a")] extern static void local2<T2>(); // 6 Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(25, 18), // (30,18): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type. // [DllImport("a")] extern static void local1(); // 7 Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(30, 18), // (31,18): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type. // [DllImport("a")] extern static void local2<T>(); // 8 Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(31, 18), // (35,22): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type. // [DllImport("a")] extern static void local1(); // 9 Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(35, 22), // (36,22): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type. // [DllImport("a")] extern static void local2<T2>(); // 10 Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(36, 22), // (41,22): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type. // [DllImport("a")] extern static void local1(); // 11 Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(41, 22), // (42,22): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type. // [DllImport("a")] extern static void local2<T2>(); // 12 Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(42, 22)); } [Fact] public void LocalFunctionExtern_NoImplementationWarning_Attribute() { const string text = @" using System.Runtime.InteropServices; class Attr : System.Attribute { } class C { void M() { #pragma warning disable 8321 // Unreferenced local function static extern void local1(); // 1 static extern void local2() { } // 2 [DllImport(""a"")] static extern void local3(); [Attr] static extern void local4(); } } "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (12,28): warning CS0626: Method, operator, or accessor 'local1()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // static extern void local1(); // 1 Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "local1").WithArguments("local1()").WithLocation(12, 28), // (13,28): error CS0179: 'local2()' cannot be extern and declare a body // static extern void local2() { } // 2 Diagnostic(ErrorCode.ERR_ExternHasBody, "local2").WithArguments("local2()").WithLocation(13, 28)); } [Fact] public void LocalFunctionExtern_Errors() { const string text = @" class C { #pragma warning disable 8321 // Unreferenced local function void M1() { void local1(); // 1 static extern void local1(); // 2, 3 } void M2() { void local1(); // 4 static extern void local1() { } // 5 } } "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,14): error CS8112: Local function 'local1()' must either have a body or be marked 'static extern'. // void local1(); // 1 Diagnostic(ErrorCode.ERR_LocalFunctionMissingBody, "local1").WithArguments("local1()").WithLocation(8, 14), // (9,28): error CS0128: A local variable or function named 'local1' is already defined in this scope // static extern void local1(); // 2, 3 Diagnostic(ErrorCode.ERR_LocalDuplicate, "local1").WithArguments("local1").WithLocation(9, 28), // (9,28): warning CS0626: Method, operator, or accessor 'local1()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // static extern void local1(); // 2, 3 Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "local1").WithArguments("local1()").WithLocation(9, 28), // (14,14): error CS8112: Local function 'local1()' must either have a body or be marked 'static extern'. // void local1(); // 4 Diagnostic(ErrorCode.ERR_LocalFunctionMissingBody, "local1").WithArguments("local1()").WithLocation(14, 14), // (15,28): error CS0128: A local variable or function named 'local1' is already defined in this scope // static extern void local1() { } // 5 Diagnostic(ErrorCode.ERR_LocalDuplicate, "local1").WithArguments("local1").WithLocation(15, 28)); } [Fact] public void ComImport_Class() { const string text = @" using System; using System.Runtime.InteropServices; [ComImport, Guid(""00020813-0000-0000-c000-000000000046"")] class C { void M() // 1 { #pragma warning disable 8321 // Unreferenced local function void local1() { } } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (8,10): error CS0423: Since 'C' has the ComImport attribute, 'C.M()' must be extern or abstract // void M() // 1 Diagnostic(ErrorCode.ERR_ComImportWithImpl, "M").WithArguments("C.M()", "C").WithLocation(8, 10)); } [Fact] public void UnsafeLocal() { var source = @" class C { void M() { var bytesA = local(); unsafe byte[] local() { var bytes = new byte[sizeof(int)]; fixed (byte* ptr = &bytes[0]) { *(int*)ptr = sizeof(int); } return bytes; } } }"; var comp = CreateCompilation(source); Assert.Empty(comp.GetDeclarationDiagnostics()); comp.VerifyDiagnostics( // (8,23): error CS0227: Unsafe code may only appear if compiling with /unsafe // unsafe byte[] local() Diagnostic(ErrorCode.ERR_IllegalUnsafe, "local").WithLocation(8, 23) ); var compWithUnsafe = CreateCompilation(source, options: TestOptions.UnsafeDebugDll); compWithUnsafe.VerifyDiagnostics(); } [Fact] public void LocalInUnsafeStruct() { var source = @" unsafe struct C { void A() { var bytesA = local(); var bytesB = B(); byte[] local() { var bytes = new byte[sizeof(int)]; fixed (byte* ptr = &bytes[0]) { *(int*)ptr = sizeof(int); } return bytes; } } byte[] B() { var bytes = new byte[sizeof(long)]; fixed (byte* ptr = &bytes[0]) { *(long*)ptr = sizeof(long); } return bytes; } }"; // no need to declare local function `local` or method `B` as unsafe var compWithUnsafe = CreateCompilation(source, options: TestOptions.UnsafeDebugDll); compWithUnsafe.VerifyDiagnostics(); } [Fact] public void LocalInUnsafeBlock() { var source = @" struct C { void A() { unsafe { var bytesA = local(); byte[] local() { var bytes = new byte[sizeof(int)]; fixed (byte* ptr = &bytes[0]) { *(int*)ptr = sizeof(int); } return bytes; } } } }"; // no need to declare local function `local` as unsafe var compWithUnsafe = CreateCompilation(source, options: TestOptions.UnsafeDebugDll); compWithUnsafe.VerifyDiagnostics(); } [Fact] public void ConstraintBinding() { var comp = CreateCompilation(@" class C { void M() { void Local<T, U>() where T : U where U : class { } Local<object, object>(); } }"); comp.VerifyDiagnostics(); } [Fact] public void ConstraintBinding2() { var comp = CreateCompilation(@" class C { void M() { void Local<T, U>(T t) where T : U where U : t { } Local<object, object>(null); } }"); comp.VerifyDiagnostics( // (8,23): error CS0246: The type or namespace name 't' could not be found (are you missing a using directive or an assembly reference?) // where U : t Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "t").WithArguments("t").WithLocation(8, 23), // (11,9): error CS0311: The type 'object' cannot be used as type parameter 'U' in the generic type or method 'Local<T, U>(T)'. There is no implicit reference conversion from 'object' to 't'. // Local<object, object>(null); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "Local<object, object>").WithArguments("Local<T, U>(T)", "t", "U", "object").WithLocation(11, 9)); } [Fact] [WorkItem(17014, "https://github.com/dotnet/roslyn/pull/17014")] public void RecursiveLocalFuncsAsParameterTypes() { var comp = CreateCompilation(@" class C { void M() { int L(L2 l2) => 0; int L2(L l1) => 0; } }"); comp.VerifyDiagnostics( // (6,15): error CS0246: The type or namespace name 'L2' could not be found (are you missing a using directive or an assembly reference?) // int L(L2 l2) => 0; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "L2").WithArguments("L2").WithLocation(6, 15), // (7,16): error CS0246: The type or namespace name 'L' could not be found (are you missing a using directive or an assembly reference?) // int L2(L l1) => 0; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "L").WithArguments("L").WithLocation(7, 16), // (6,13): warning CS8321: The local function 'L' is declared but never used // int L(L2 l2) => 0; Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "L").WithArguments("L").WithLocation(6, 13), // (7,13): warning CS8321: The local function 'L2' is declared but never used // int L2(L l1) => 0; Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "L2").WithArguments("L2").WithLocation(7, 13)); } [Fact] [WorkItem(16451, "https://github.com/dotnet/roslyn/issues/16451")] public void BadGenericConstraint() { var comp = CreateCompilation(@" class C { public void M<T>(T value) where T : class, object { } }"); comp.VerifyDiagnostics( // (4,48): error CS0702: Constraint cannot be special class 'object' // public void M<T>(T value) where T : class, object { } Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object").WithArguments("object").WithLocation(4, 48) ); } [Fact] [WorkItem(16451, "https://github.com/dotnet/roslyn/issues/16451")] public void RecursiveDefaultParameter() { var comp = CreateCompilation(@" class C { public static void Main() { int Local(int j = Local()) => 0; Local(); } }"); comp.VerifyDiagnostics( // (6,27): error CS1736: Default parameter value for 'j' must be a compile-time constant // int Local(int j = Local()) => 0; Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "Local()").WithArguments("j").WithLocation(6, 27)); comp.DeclarationDiagnostics.Verify(); } [Fact] [WorkItem(16451, "https://github.com/dotnet/roslyn/issues/16451")] public void RecursiveDefaultParameter2() { var comp = CreateCompilation(@" using System; class C { void M() { int Local(Action a = Local) => 0; Local(); } }"); comp.VerifyDiagnostics( // (7,30): error CS1736: Default parameter value for 'a' must be a compile-time constant // int Local(Action a = Local) => 0; Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "Local").WithArguments("a").WithLocation(7, 30)); comp.DeclarationDiagnostics.Verify(); } [Fact] [WorkItem(16451, "https://github.com/dotnet/roslyn/issues/16451")] public void MutuallyRecursiveDefaultParameters() { var comp = CreateCompilation(@" class C { void M() { int Local1(int p = Local2()) => 0; int Local2(int p = Local1()) => 0; Local1(); Local2(); } }"); comp.VerifyDiagnostics( // (6,28): error CS1736: Default parameter value for 'p' must be a compile-time constant // int Local1(int p = Local2()) => 0; Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "Local2()").WithArguments("p").WithLocation(6, 28), // (7,28): error CS1736: Default parameter value for 'p' must be a compile-time constant // int Local2(int p = Local1()) => 0; Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "Local1()").WithArguments("p").WithLocation(7, 28)); comp.DeclarationDiagnostics.Verify(); } [Fact] public void FetchLocalFunctionSymbolThroughLocal() { var tree = SyntaxFactory.ParseSyntaxTree(@" using System; class C { public void M() { void Local<[A, B, CLSCompliant, D]T>() { var x = new object(); } Local<int>(); } }"); var comp = CreateCompilation(tree); comp.DeclarationDiagnostics.Verify(); comp.VerifyDiagnostics( // (7,21): error CS0246: The type or namespace name 'AAttribute' could not be found (are you missing a using directive or an assembly reference?) // void Local<[A, B, CLSCompliant, D]T>() Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A").WithArguments("AAttribute").WithLocation(7, 21), // (7,21): error CS0246: The type or namespace name 'A' could not be found (are you missing a using directive or an assembly reference?) // void Local<[A, B, CLSCompliant, D]T>() Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A").WithArguments("A").WithLocation(7, 21), // (7,24): error CS0246: The type or namespace name 'BAttribute' could not be found (are you missing a using directive or an assembly reference?) // void Local<[A, B, CLSCompliant, D]T>() Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "B").WithArguments("BAttribute").WithLocation(7, 24), // (7,24): error CS0246: The type or namespace name 'B' could not be found (are you missing a using directive or an assembly reference?) // void Local<[A, B, CLSCompliant, D]T>() Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "B").WithArguments("B").WithLocation(7, 24), // (7,41): error CS0246: The type or namespace name 'DAttribute' could not be found (are you missing a using directive or an assembly reference?) // void Local<[A, B, CLSCompliant, D]T>() Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "D").WithArguments("DAttribute").WithLocation(7, 41), // (7,41): error CS0246: The type or namespace name 'D' could not be found (are you missing a using directive or an assembly reference?) // void Local<[A, B, CLSCompliant, D]T>() Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "D").WithArguments("D").WithLocation(7, 41), // (7,27): error CS7036: There is no argument given that corresponds to the required formal parameter 'isCompliant' of 'CLSCompliantAttribute.CLSCompliantAttribute(bool)' // void Local<[A, B, CLSCompliant, D]T>() Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "CLSCompliant").WithArguments("isCompliant", "System.CLSCompliantAttribute.CLSCompliantAttribute(bool)").WithLocation(7, 27)); var model = comp.GetSemanticModel(tree); var x = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(v => v.Identifier.ValueText == "x").Single(); var localSymbol = model.GetDeclaredSymbol(x).ContainingSymbol.GetSymbol<LocalFunctionSymbol>(); var typeParam = localSymbol.TypeParameters.Single(); var attrs = typeParam.GetAttributes(); Assert.True(attrs[0].AttributeClass.IsErrorType()); Assert.True(attrs[1].AttributeClass.IsErrorType()); Assert.False(attrs[2].AttributeClass.IsErrorType()); Assert.Equal(comp.GlobalNamespace .GetMember<NamespaceSymbol>("System") .GetMember<NamedTypeSymbol>("CLSCompliantAttribute"), attrs[2].AttributeClass); Assert.True(attrs[3].AttributeClass.IsErrorType()); comp.DeclarationDiagnostics.Verify(); } [Fact] public void TypeParameterAttributesInSemanticModel() { var comp = (Compilation)CreateCompilation(@" using System; class C { public void M() { void Local<[A]T, [CLSCompliant]U>() { } } }", parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,21): error CS0246: The type or namespace name 'AAttribute' could not be found (are you missing a using directive or an assembly reference?) // void Local<[A]T, [CLSCompliant]U>() { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A").WithArguments("AAttribute").WithLocation(7, 21), // (7,21): error CS0246: The type or namespace name 'A' could not be found (are you missing a using directive or an assembly reference?) // void Local<[A]T, [CLSCompliant]U>() { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A").WithArguments("A").WithLocation(7, 21), // (7,27): error CS7036: There is no argument given that corresponds to the required formal parameter 'isCompliant' of 'CLSCompliantAttribute.CLSCompliantAttribute(bool)' // void Local<[A]T, [CLSCompliant]U>() { } Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "CLSCompliant").WithArguments("isCompliant", "System.CLSCompliantAttribute.CLSCompliantAttribute(bool)").WithLocation(7, 27), // (7,14): warning CS8321: The local function 'Local' is declared but never used // void Local<[A]T, [CLSCompliant]U>() { } Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local").WithArguments("Local").WithLocation(7, 14)); var tree = comp.SyntaxTrees.First(); var root = tree.GetRoot(); var model = comp.GetSemanticModel(tree); var a = root.DescendantNodes() .OfType<IdentifierNameSyntax>() .Where(id => id.Identifier.ValueText == "A") .Single(); Assert.Null(model.GetDeclaredSymbol(a)); var aSymbolInfo = model.GetSymbolInfo(a); Assert.Equal(0, aSymbolInfo.CandidateSymbols.Length); Assert.Null(aSymbolInfo.Symbol); var aTypeInfo = model.GetTypeInfo(a); Assert.Equal(TypeKind.Error, aTypeInfo.Type.TypeKind); Assert.Null(model.GetAliasInfo(a)); Assert.Empty(model.LookupNamespacesAndTypes(a.SpanStart, name: "A")); var clsCompliant = root.DescendantNodes() .OfType<IdentifierNameSyntax>() .Where(id => id.Identifier.ValueText == "CLSCompliant") .Single(); var clsCompliantSymbol = comp.GlobalNamespace .GetMember<INamespaceSymbol>("System") .GetTypeMember("CLSCompliantAttribute"); Assert.Null(model.GetDeclaredSymbol(clsCompliant)); // This should be null because there is no CLSCompliant ctor with no args var clsCompliantSymbolInfo = model.GetSymbolInfo(clsCompliant); Assert.Null(clsCompliantSymbolInfo.Symbol); Assert.Equal(clsCompliantSymbol.GetMember<IMethodSymbol>(".ctor"), clsCompliantSymbolInfo.CandidateSymbols.Single()); Assert.Equal(CandidateReason.OverloadResolutionFailure, clsCompliantSymbolInfo.CandidateReason); Assert.Equal(clsCompliantSymbol, model.GetTypeInfo(clsCompliant).Type); Assert.Null(model.GetAliasInfo(clsCompliant)); Assert.Equal(clsCompliantSymbol, model.LookupNamespacesAndTypes(clsCompliant.SpanStart, name: "CLSCompliantAttribute").Single()); ((CSharpCompilation)comp).DeclarationDiagnostics.Verify(); } [Fact] public void ParameterAttributesInSemanticModel() { var comp = (Compilation)CreateCompilation(@" using System; class C { public void M() { void Local([A]int x, [CLSCompliant]int y) { } } }", parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,21): error CS0246: The type or namespace name 'AAttribute' could not be found (are you missing a using directive or an assembly reference?) // void Local([A]int x, [CLSCompliant]int y) { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A").WithArguments("AAttribute").WithLocation(7, 21), // (7,21): error CS0246: The type or namespace name 'A' could not be found (are you missing a using directive or an assembly reference?) // void Local([A]int x, [CLSCompliant]int y) { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A").WithArguments("A").WithLocation(7, 21), // (7,31): error CS7036: There is no argument given that corresponds to the required formal parameter 'isCompliant' of 'CLSCompliantAttribute.CLSCompliantAttribute(bool)' // void Local([A]int x, [CLSCompliant]int y) { } Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "CLSCompliant").WithArguments("isCompliant", "System.CLSCompliantAttribute.CLSCompliantAttribute(bool)").WithLocation(7, 31), // (7,14): warning CS8321: The local function 'Local' is declared but never used // void Local([A]int x, [CLSCompliant]int y) { } Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local").WithArguments("Local").WithLocation(7, 14)); var tree = comp.SyntaxTrees.First(); var root = tree.GetRoot(); var model = comp.GetSemanticModel(tree); var a = root.DescendantNodes() .OfType<IdentifierNameSyntax>() .Where(id => id.Identifier.ValueText == "A") .Single(); Assert.Null(model.GetDeclaredSymbol(a)); var aSymbolInfo = model.GetSymbolInfo(a); Assert.Equal(0, aSymbolInfo.CandidateSymbols.Length); Assert.Null(aSymbolInfo.Symbol); var aTypeInfo = model.GetTypeInfo(a); Assert.Equal(TypeKind.Error, aTypeInfo.Type.TypeKind); Assert.Null(model.GetAliasInfo(a)); Assert.Empty(model.LookupNamespacesAndTypes(a.SpanStart, name: "A")); var clsCompliant = root.DescendantNodes() .OfType<IdentifierNameSyntax>() .Where(id => id.Identifier.ValueText == "CLSCompliant") .Single(); var clsCompliantSymbol = comp.GlobalNamespace .GetMember<INamespaceSymbol>("System") .GetTypeMember("CLSCompliantAttribute"); Assert.Null(model.GetDeclaredSymbol(clsCompliant)); // This should be null because there is no CLSCompliant ctor with no args var clsCompliantSymbolInfo = model.GetSymbolInfo(clsCompliant); Assert.Null(clsCompliantSymbolInfo.Symbol); Assert.Equal(clsCompliantSymbol.GetMember<IMethodSymbol>(".ctor"), clsCompliantSymbolInfo.CandidateSymbols.Single()); Assert.Equal(CandidateReason.OverloadResolutionFailure, clsCompliantSymbolInfo.CandidateReason); Assert.Equal(clsCompliantSymbol, model.GetTypeInfo(clsCompliant).Type); Assert.Null(model.GetAliasInfo(clsCompliant)); Assert.Equal(clsCompliantSymbol, model.LookupNamespacesAndTypes(clsCompliant.SpanStart, name: "CLSCompliantAttribute").Single()); ((CSharpCompilation)comp).DeclarationDiagnostics.Verify(); } [Fact] public void LocalFunctionAttribute_TypeParameter_Errors() { var tree = SyntaxFactory.ParseSyntaxTree(@" using System; class C { public void M() { void Local<[A, B, CLSCompliant, D]T>() { } Local<int>(); } }", options: TestOptions.Regular9); var comp = CreateCompilation(tree); comp.DeclarationDiagnostics.Verify(); comp.VerifyDiagnostics( // (7,21): error CS0246: The type or namespace name 'AAttribute' could not be found (are you missing a using directive or an assembly reference?) // void Local<[A, B, CLSCompliant, D]T>() { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A").WithArguments("AAttribute").WithLocation(7, 21), // (7,21): error CS0246: The type or namespace name 'A' could not be found (are you missing a using directive or an assembly reference?) // void Local<[A, B, CLSCompliant, D]T>() { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A").WithArguments("A").WithLocation(7, 21), // (7,24): error CS0246: The type or namespace name 'BAttribute' could not be found (are you missing a using directive or an assembly reference?) // void Local<[A, B, CLSCompliant, D]T>() { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "B").WithArguments("BAttribute").WithLocation(7, 24), // (7,24): error CS0246: The type or namespace name 'B' could not be found (are you missing a using directive or an assembly reference?) // void Local<[A, B, CLSCompliant, D]T>() { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "B").WithArguments("B").WithLocation(7, 24), // (7,41): error CS0246: The type or namespace name 'DAttribute' could not be found (are you missing a using directive or an assembly reference?) // void Local<[A, B, CLSCompliant, D]T>() { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "D").WithArguments("DAttribute").WithLocation(7, 41), // (7,41): error CS0246: The type or namespace name 'D' could not be found (are you missing a using directive or an assembly reference?) // void Local<[A, B, CLSCompliant, D]T>() { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "D").WithArguments("D").WithLocation(7, 41), // (7,27): error CS7036: There is no argument given that corresponds to the required formal parameter 'isCompliant' of 'CLSCompliantAttribute.CLSCompliantAttribute(bool)' // void Local<[A, B, CLSCompliant, D]T>() { } Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "CLSCompliant").WithArguments("isCompliant", "System.CLSCompliantAttribute.CLSCompliantAttribute(bool)").WithLocation(7, 27)); var localDecl = tree.FindNodeOrTokenByKind(SyntaxKind.LocalFunctionStatement); var model = comp.GetSemanticModel(tree); var localSymbol = Assert.IsType<LocalFunctionSymbol>(model.GetDeclaredSymbol(localDecl.AsNode()).GetSymbol()); var typeParam = localSymbol.TypeParameters.Single(); var attrs = typeParam.GetAttributes(); Assert.True(attrs[0].AttributeClass.IsErrorType()); Assert.True(attrs[1].AttributeClass.IsErrorType()); Assert.False(attrs[2].AttributeClass.IsErrorType()); Assert.Equal(comp.GlobalNamespace .GetMember<NamespaceSymbol>("System") .GetMember<NamedTypeSymbol>("CLSCompliantAttribute"), attrs[2].AttributeClass); Assert.True(attrs[3].AttributeClass.IsErrorType()); comp.DeclarationDiagnostics.Verify(); } [Fact] public void LocalFunctionAttribute_Parameter_Errors() { var tree = SyntaxFactory.ParseSyntaxTree(@" using System; class C { public void M() { void Local([A, B]int x, [CLSCompliant]string s = """") { } Local(0); } }", options: TestOptions.Regular9); var comp = CreateCompilation(tree); comp.DeclarationDiagnostics.Verify(); comp.VerifyDiagnostics( // (7,21): error CS0246: The type or namespace name 'AAttribute' could not be found (are you missing a using directive or an assembly reference?) // void Local([A, B]int x, [CLSCompliant]string s = "") { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A").WithArguments("AAttribute").WithLocation(7, 21), // (7,21): error CS0246: The type or namespace name 'A' could not be found (are you missing a using directive or an assembly reference?) // void Local([A, B]int x, [CLSCompliant]string s = "") { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A").WithArguments("A").WithLocation(7, 21), // (7,24): error CS0246: The type or namespace name 'BAttribute' could not be found (are you missing a using directive or an assembly reference?) // void Local([A, B]int x, [CLSCompliant]string s = "") { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "B").WithArguments("BAttribute").WithLocation(7, 24), // (7,24): error CS0246: The type or namespace name 'B' could not be found (are you missing a using directive or an assembly reference?) // void Local([A, B]int x, [CLSCompliant]string s = "") { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "B").WithArguments("B").WithLocation(7, 24), // (7,34): error CS7036: There is no argument given that corresponds to the required formal parameter 'isCompliant' of 'CLSCompliantAttribute.CLSCompliantAttribute(bool)' // void Local([A, B]int x, [CLSCompliant]string s = "") { } Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "CLSCompliant").WithArguments("isCompliant", "System.CLSCompliantAttribute.CLSCompliantAttribute(bool)").WithLocation(7, 34)); var localDecl = tree.FindNodeOrTokenByKind(SyntaxKind.LocalFunctionStatement); var model = comp.GetSemanticModel(tree); var localSymbol = Assert.IsType<LocalFunctionSymbol>(model.GetDeclaredSymbol(localDecl.AsNode()).GetSymbol()); var param = localSymbol.Parameters[0]; var attrs = param.GetAttributes(); Assert.True(attrs[0].AttributeClass.IsErrorType()); Assert.True(attrs[1].AttributeClass.IsErrorType()); param = localSymbol.Parameters[1]; attrs = param.GetAttributes(); Assert.Equal(comp.GlobalNamespace .GetMember<NamespaceSymbol>("System") .GetMember<NamedTypeSymbol>("CLSCompliantAttribute"), attrs[0].AttributeClass); comp.DeclarationDiagnostics.Verify(); } [Fact] public void LocalFunctionDisallowedAttributes() { var source = @" using System.Runtime.CompilerServices; namespace System.Runtime.CompilerServices { public class IsReadOnlyAttribute : System.Attribute { } public class IsUnmanagedAttribute : System.Attribute { } public class IsByRefLikeAttribute : System.Attribute { } public class NullableContextAttribute : System.Attribute { public NullableContextAttribute(byte b) { } } } class C { void M() { local1(); [IsReadOnly] // 1 [IsUnmanaged] // 2 [IsByRefLike] // 3 [Extension] // 4 [NullableContext(0)] // 5 void local1() { } } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (18,10): error CS8335: Do not use 'System.Runtime.CompilerServices.IsReadOnlyAttribute'. This is reserved for compiler usage. // [IsReadOnly] // 1 Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsReadOnly").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute").WithLocation(18, 10), // (19,10): error CS8335: Do not use 'System.Runtime.CompilerServices.IsUnmanagedAttribute'. This is reserved for compiler usage. // [IsUnmanaged] // 2 Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsUnmanaged").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute").WithLocation(19, 10), // (20,10): error CS8335: Do not use 'System.Runtime.CompilerServices.IsByRefLikeAttribute'. This is reserved for compiler usage. // [IsByRefLike] // 3 Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsByRefLike").WithArguments("System.Runtime.CompilerServices.IsByRefLikeAttribute").WithLocation(20, 10), // (21,10): error CS1112: Do not use 'System.Runtime.CompilerServices.ExtensionAttribute'. Use the 'this' keyword instead. // [Extension] // 4 Diagnostic(ErrorCode.ERR_ExplicitExtension, "Extension").WithLocation(21, 10), // (22,10): error CS8335: Do not use 'System.Runtime.CompilerServices.NullableContextAttribute'. This is reserved for compiler usage. // [NullableContext(0)] // 5 Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "NullableContext(0)").WithArguments("System.Runtime.CompilerServices.NullableContextAttribute").WithLocation(22, 10)); } [Fact] public void LocalFunctionDisallowedSecurityAttributes() { var source = @" using System.Security; class C { void M() { local1(); [SecurityCritical] // 1 [SecuritySafeCriticalAttribute] // 2 async void local1() // 3 { } } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (10,10): error CS4030: Security attribute 'SecurityCritical' cannot be applied to an Async method. // [SecurityCritical] // 1 Diagnostic(ErrorCode.ERR_SecurityCriticalOrSecuritySafeCriticalOnAsync, "SecurityCritical").WithArguments("SecurityCritical").WithLocation(10, 10), // (11,10): error CS4030: Security attribute 'SecuritySafeCriticalAttribute' cannot be applied to an Async method. // [SecuritySafeCriticalAttribute] // 2 Diagnostic(ErrorCode.ERR_SecurityCriticalOrSecuritySafeCriticalOnAsync, "SecuritySafeCriticalAttribute").WithArguments("SecuritySafeCriticalAttribute").WithLocation(11, 10), // (12,20): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread. // async void local1() // 3 Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "local1").WithLocation(12, 20)); } [Fact] public void TypeParameterBindingScope() { var src = @" class C { public void M() { { int T = 0; // Should not have error int Local<T>() => 0; // Should conflict with above Local<int>(); T++; } { int T<T>() => 0; T<int>(); } { int Local<T, T>() => 0; Local<int, int>(); } } public void M2<T>() { { int Local<T>() => 0; Local<int>(); } { int Local1<V>() { int Local2<V>() => 0; return Local2<int>(); } Local1<int>(); } { int T() => 0; T(); } { int Local1<V>() { int V() => 0; return V(); } Local1<int>(); } { int Local1<V>() { int Local2<U>() { // Conflicts with method type parameter int T() => 0; return T(); } return Local2<int>(); } Local1<int>(); } { int Local1<V>() { int Local2<U>() { // Shadows M.2<T> int Local3<T>() => 0; return Local3<int>(); } return Local2<int>(); } Local1<int>(); } } public void V<V>() { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics( // (9,23): error CS0136: A local or parameter named 'T' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int Local<T>() => 0; // Should conflict with above Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "T").WithArguments("T").WithLocation(9, 23), // (14,19): error CS0136: A local or parameter named 'T' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int T<T>() => 0; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "T").WithArguments("T").WithLocation(14, 19), // (18,26): error CS0692: Duplicate type parameter 'T' // int Local<T, T>() => 0; Diagnostic(ErrorCode.ERR_DuplicateTypeParameter, "T").WithArguments("T").WithLocation(18, 26), // (25,23): warning CS8387: Type parameter 'T' has the same name as the type parameter from outer method 'C.M2<T>()' // int Local<T>() => 0; Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterMethodTypeParameter, "T").WithArguments("T", "C.M2<T>()").WithLocation(25, 23), // (31,28): warning CS8387: Type parameter 'V' has the same name as the type parameter from outer method 'Local1<V>()' // int Local2<V>() => 0; Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterMethodTypeParameter, "V").WithArguments("V", "Local1<V>()").WithLocation(31, 28), // (37,17): error CS0412: 'T': a parameter, local variable, or local function cannot have the same name as a method type parameter // int T() => 0; Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "T").WithArguments("T").WithLocation(37, 17), // (43,21): error CS0412: 'V': a parameter, local variable, or local function cannot have the same name as a method type parameter // int V() => 0; Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "V").WithArguments("V").WithLocation(43, 21), // (54,25): error CS0412: 'T': a parameter, local variable, or local function cannot have the same name as a method type parameter // int T() => 0; Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "T").WithArguments("T").WithLocation(54, 25), // (67,32): warning CS8387: Type parameter 'T' has the same name as the type parameter from outer method 'C.M2<T>()' // int Local3<T>() => 0; Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterMethodTypeParameter, "T").WithArguments("T", "C.M2<T>()").WithLocation(67, 32)); comp = CreateCompilation(src, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (18,26): error CS0692: Duplicate type parameter 'T' // int Local<T, T>() => 0; Diagnostic(ErrorCode.ERR_DuplicateTypeParameter, "T").WithArguments("T").WithLocation(18, 26), // (25,23): warning CS8387: Type parameter 'T' has the same name as the type parameter from outer method 'C.M2<T>()' // int Local<T>() => 0; Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterMethodTypeParameter, "T").WithArguments("T", "C.M2<T>()").WithLocation(25, 23), // (31,28): warning CS8387: Type parameter 'V' has the same name as the type parameter from outer method 'Local1<V>()' // int Local2<V>() => 0; Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterMethodTypeParameter, "V").WithArguments("V", "Local1<V>()").WithLocation(31, 28), // (37,17): error CS0412: 'T': a parameter, local variable, or local function cannot have the same name as a method type parameter // int T() => 0; Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "T").WithArguments("T").WithLocation(37, 17), // (43,21): error CS0412: 'V': a parameter, local variable, or local function cannot have the same name as a method type parameter // int V() => 0; Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "V").WithArguments("V").WithLocation(43, 21), // (67,32): warning CS8387: Type parameter 'T' has the same name as the type parameter from outer method 'C.M2<T>()' // int Local3<T>() => 0; Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterMethodTypeParameter, "T").WithArguments("T", "C.M2<T>()").WithLocation(67, 32)); } [Fact] public void LocalFuncAndTypeParameterOnType() { var comp = CreateCompilation(@" class C2<T> { public void M() { { int Local1() { int Local2<T>() => 0; return Local2<int>(); } Local1(); } { int Local1() { int Local2() { // Shadows type parameter int T() => 0; // Type parameter resolves in type only context T t = default(T); // Ambiguous context chooses local T.M(); // Call chooses local return T(); } return Local2(); } Local1(); } } }"); comp.VerifyDiagnostics( // (9,28): warning CS0693: Type parameter 'T' has the same name as the type parameter from outer type 'C2<T>' // int Local2<T>() => 0; Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, "T").WithArguments("T", "C2<T>").WithLocation(9, 28), // (26,21): error CS0119: 'T()' is a method, which is not valid in the given context // T.M(); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T()", "method").WithLocation(26, 21), // (23,23): warning CS0219: The variable 't' is assigned but its value is never used // T t = default(T); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "t").WithArguments("t").WithLocation(23, 23)); } [Fact] public void RefArgsInIteratorLocalFuncs() { var src = @" using System; using System.Collections.Generic; class C { public void M1() { IEnumerable<int> Local(ref int a) { yield break; } int x = 0; Local(ref x); } public void M2() { Action a = () => { IEnumerable<int> Local(ref int x) { yield break; } int y = 0; Local(ref y); return; }; a(); } public Func<int> M3() => (() => { IEnumerable<int> Local(ref int a) { yield break; } int x = 0; Local(ref x); return 0; }); public IEnumerable<int> M4(ref int a) { yield return new Func<int>(() => { IEnumerable<int> Local(ref int b) { yield break; } int x = 0; Local(ref x); return 0; })(); } }"; VerifyDiagnostics(src, // (8,40): error CS1623: Iterators cannot have ref, in or out parameters // IEnumerable<int> Local(ref int a) { yield break; } Diagnostic(ErrorCode.ERR_BadIteratorArgType, "a").WithLocation(8, 40), // (17,44): error CS1623: Iterators cannot have ref, in or out parameters // IEnumerable<int> Local(ref int x) { yield break; } Diagnostic(ErrorCode.ERR_BadIteratorArgType, "x").WithLocation(17, 44), // (27,40): error CS1623: Iterators cannot have ref, in or out parameters // IEnumerable<int> Local(ref int a) { yield break; } Diagnostic(ErrorCode.ERR_BadIteratorArgType, "a").WithLocation(27, 40), // (33,40): error CS1623: Iterators cannot have ref, in or out parameters // public IEnumerable<int> M4(ref int a) Diagnostic(ErrorCode.ERR_BadIteratorArgType, "a").WithLocation(33, 40), // (37,48): error CS1623: Iterators cannot have ref, in or out parameters // IEnumerable<int> Local(ref int b) { yield break; } Diagnostic(ErrorCode.ERR_BadIteratorArgType, "b").WithLocation(37, 48)); } [Fact] public void UnsafeArgsInIteratorLocalFuncs() { var src = @" using System; using System.Collections.Generic; class C { public unsafe void M1() { IEnumerable<int> Local(int* a) { yield break; } int x = 0; Local(&x); } public unsafe void M2() { Action a = () => { IEnumerable<int> Local(int* x) { yield break; } int y = 0; Local(&y); return; }; a(); } public unsafe Func<int> M3() => (() => { IEnumerable<int> Local(int* a) { yield break; } int x = 0; Local(&x); return 0; }); public unsafe IEnumerable<int> M4(int* a) { yield return new Func<int>(() => { IEnumerable<int> Local(int* b) { yield break; } int x = 0; Local(&x); return 0; })(); } }"; CreateCompilation(src, options: TestOptions.UnsafeDebugDll) .VerifyDiagnostics( // (8,37): error CS1637: Iterators cannot have unsafe parameters or yield types // IEnumerable<int> Local(int* a) { yield break; } Diagnostic(ErrorCode.ERR_UnsafeIteratorArgType, "a").WithLocation(8, 37), // (17,41): error CS1637: Iterators cannot have unsafe parameters or yield types // IEnumerable<int> Local(int* x) { yield break; } Diagnostic(ErrorCode.ERR_UnsafeIteratorArgType, "x").WithLocation(17, 41), // (27,37): error CS1637: Iterators cannot have unsafe parameters or yield types // IEnumerable<int> Local(int* a) { yield break; } Diagnostic(ErrorCode.ERR_UnsafeIteratorArgType, "a").WithLocation(27, 37), // (33,44): error CS1637: Iterators cannot have unsafe parameters or yield types // public unsafe IEnumerable<int> M4(int* a) Diagnostic(ErrorCode.ERR_UnsafeIteratorArgType, "a").WithLocation(33, 44), // (33,36): error CS1629: Unsafe code may not appear in iterators // public unsafe IEnumerable<int> M4(int* a) Diagnostic(ErrorCode.ERR_IllegalInnerUnsafe, "M4").WithLocation(33, 36), // (37,40): error CS1629: Unsafe code may not appear in iterators // IEnumerable<int> Local(int* b) { yield break; } Diagnostic(ErrorCode.ERR_IllegalInnerUnsafe, "int*").WithLocation(37, 40), // (39,23): error CS1629: Unsafe code may not appear in iterators // Local(&x); Diagnostic(ErrorCode.ERR_IllegalInnerUnsafe, "&x").WithLocation(39, 23), // (39,17): error CS1629: Unsafe code may not appear in iterators // Local(&x); Diagnostic(ErrorCode.ERR_IllegalInnerUnsafe, "Local(&x)").WithLocation(39, 17), // (37,45): error CS1637: Iterators cannot have unsafe parameters or yield types // IEnumerable<int> Local(int* b) { yield break; } Diagnostic(ErrorCode.ERR_UnsafeIteratorArgType, "b").WithLocation(37, 45)); } [Fact] [WorkItem(13193, "https://github.com/dotnet/roslyn/issues/13193")] public void LocalFunctionConflictingName() { var comp = CreateCompilation(@" class C { public void M<TLocal>() { void TLocal() { } TLocal(); } public void M(int Local) { void Local() { } Local(); } public void M() { int local = 0; void local() { } local(); } }"); comp.VerifyDiagnostics( // (6,14): error CS0412: 'TLocal': a parameter, local variable, or local function cannot have the same name as a method type parameter // void TLocal() { } Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "TLocal").WithArguments("TLocal").WithLocation(6, 14), // (11,14): error CS0136: A local or parameter named 'Local' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // void Local() { } Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "Local").WithArguments("Local").WithLocation(11, 14), // (18,14): error CS0128: A local variable or function named 'local' is already defined in this scope // void local() { } Diagnostic(ErrorCode.ERR_LocalDuplicate, "local").WithArguments("local").WithLocation(18, 14), // (16,13): warning CS0219: The variable 'local' is assigned but its value is never used // int local = 0; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "local").WithArguments("local").WithLocation(16, 13)); } [Fact] public void ForgotSemicolonLocalFunctionsMistake() { var src = @" class C { public void M1() { // forget closing brace public void BadLocal1() { this.BadLocal2(); } public void BadLocal2() { } public int P => 0; }"; VerifyDiagnostics(src, // (8,5): error CS0106: The modifier 'public' is not valid for this item // public void BadLocal1() Diagnostic(ErrorCode.ERR_BadMemberFlag, "public").WithArguments("public").WithLocation(8, 5), // (13,5): error CS0106: The modifier 'public' is not valid for this item // public void BadLocal2() Diagnostic(ErrorCode.ERR_BadMemberFlag, "public").WithArguments("public").WithLocation(13, 5), // (15,6): error CS1513: } expected // } Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(15, 6), // (10,14): error CS1061: 'C' does not contain a definition for 'BadLocal2' and no extension method 'BadLocal2' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?) // this.BadLocal2(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "BadLocal2").WithArguments("C", "BadLocal2").WithLocation(10, 14), // (8,17): warning CS8321: The local function 'BadLocal1' is declared but never used // public void BadLocal1() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "BadLocal1").WithArguments("BadLocal1").WithLocation(8, 17), // (13,17): warning CS8321: The local function 'BadLocal2' is declared but never used // public void BadLocal2() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "BadLocal2").WithArguments("BadLocal2").WithLocation(13, 17)); } [Fact] public void VarLocalFunction() { var src = @" class C { void M() { var local() => 0; int x = local(); } }"; VerifyDiagnostics(src, // (6,9): error CS0825: The contextual keyword 'var' may only appear within a local variable declaration or in script code // var local() => 0; Diagnostic(ErrorCode.ERR_TypeVarNotFound, "var").WithLocation(6, 9)); } [Fact] public void VarLocalFunction2() { var comp = CreateCompilation(@" class C { private class var { } void M() { var local() => new var(); var x = local(); } }", parseOptions: DefaultParseOptions); comp.VerifyDiagnostics(); } [Fact] [CompilerTrait(CompilerFeature.Params)] public void BadParams() { var source = @" using System; class Program { static void Main(string[] args) { void Params(params int x) { Console.WriteLine(x); } Params(2); } } "; VerifyDiagnostics(source, // (8,21): error CS0225: The params parameter must be a single dimensional array // void Params(params int x) Diagnostic(ErrorCode.ERR_ParamsMustBeArray, "params").WithLocation(8, 21) ); } [Fact] public void BadRefWithDefault() { var source = @" class Program { static void Main(string[] args) { void RefOut(ref int x = 2) { x++; } int y = 2; RefOut(ref y); } } "; VerifyDiagnostics(source, // (6,21): error CS1741: A ref or out parameter cannot have a default value // void RefOut(ref int x = 2) Diagnostic(ErrorCode.ERR_RefOutDefaultValue, "ref").WithLocation(6, 21) ); } [Fact] public void BadDefaultValueType() { var source = @" using System; class Program { static void Main(string[] args) { void NamedOptional(string x = 2) { Console.WriteLine(x); } NamedOptional(""2""); } } "; VerifyDiagnostics(source, // (8,35): error CS1750: A value of type 'int' cannot be used as a default parameter because there are no standard conversions to type 'string' // void NamedOptional(string x = 2) Diagnostic(ErrorCode.ERR_NoConversionForDefaultParam, "x").WithArguments("int", "string").WithLocation(8, 35) ); } [Fact] public void CallerMemberName() { var comp = CreateCompilationWithMscorlib46(@" using System; using System.Runtime.CompilerServices; class C { static void Main() { void CallerMemberName([CallerMemberName] string s = null) { Console.Write(s); } void LocalFuncName() { CallerMemberName(); } LocalFuncName(); Console.Write(' '); CallerMemberName(); } }", parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); } [Fact] public void BadCallerMemberName() { var source = @" using System; using System.Runtime.CompilerServices; class Program { static void Main(string[] args) { void CallerMemberName([CallerMemberName] int s = 2) // 1 { Console.WriteLine(s); } CallerMemberName(); // 2 } } "; CreateCompilationWithMscorlib45AndCSharp(source, parseOptions: TestOptions.Regular9).VerifyDiagnostics( // (9,32): error CS4019: CallerMemberNameAttribute cannot be applied because there are no standard conversions from type 'string' to type 'int' // void CallerMemberName([CallerMemberName] int s = 2) // 1 Diagnostic(ErrorCode.ERR_NoConversionForCallerMemberNameParam, "CallerMemberName").WithArguments("string", "int").WithLocation(9, 32), // (13,9): error CS0029: Cannot implicitly convert type 'string' to 'int' // CallerMemberName(); // 2 Diagnostic(ErrorCode.ERR_NoImplicitConv, "CallerMemberName()").WithArguments("string", "int").WithLocation(13, 9)); } [WorkItem(10708, "https://github.com/dotnet/roslyn/issues/10708")] [CompilerTrait(CompilerFeature.Dynamic, CompilerFeature.Params)] [Fact] public void DynamicArgumentToParams() { var src = @" using System; class C { static void Main() { void L1(int x = 0, params int[] ys) => Console.Write(x); dynamic val = 2; L1(val, val); L1(ys: val, x: val); L1(ys: val); } }"; VerifyDiagnostics(src, // (10,9): error CS8106: Cannot pass argument with dynamic type to params parameter 'ys' of local function 'L1'. // L1(val, val); Diagnostic(ErrorCode.ERR_DynamicLocalFunctionParamsParameter, "L1(val, val)").WithArguments("ys", "L1").WithLocation(10, 9), // (11,9): error CS8106: Cannot pass argument with dynamic type to params parameter 'ys' of local function 'L1'. // L1(ys: val, x: val); Diagnostic(ErrorCode.ERR_DynamicLocalFunctionParamsParameter, "L1(ys: val, x: val)").WithArguments("ys", "L1").WithLocation(11, 9), // (12,9): error CS8106: Cannot pass argument with dynamic type to params parameter 'ys' of local function 'L1'. // L1(ys: val); Diagnostic(ErrorCode.ERR_DynamicLocalFunctionParamsParameter, "L1(ys: val)").WithArguments("ys", "L1").WithLocation(12, 9)); } [Fact] [CompilerTrait(CompilerFeature.Dynamic)] public void DynamicArgOverload() { var src = @" using System; class C { static void Main() { void Overload(int i) => Console.Write(i); void Overload(string s) => Console.Write(s); dynamic val = 2; Overload(val); } }"; VerifyDiagnostics(src, // (8,14): error CS0128: A local variable named 'Overload' is already defined in this scope // void Overload(string s) => Console.Write(s); Diagnostic(ErrorCode.ERR_LocalDuplicate, "Overload").WithArguments("Overload").WithLocation(8, 14), // (8,14): warning CS8321: The local function 'Overload' is declared but never used // void Overload(string s) => Console.Write(s); Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Overload").WithArguments("Overload").WithLocation(8, 14)); } [Fact] [CompilerTrait(CompilerFeature.Dynamic)] public void DynamicArgWrongArity() { var src = @" using System; class C { static void Main() { void Local(int i) => Console.Write(i); dynamic val = 2; Local(val, val); } }"; VerifyDiagnostics(src, // (10,9): error CS1501: No overload for method 'Local' takes 2 arguments // Local(val, val); Diagnostic(ErrorCode.ERR_BadArgCount, "Local").WithArguments("Local", "2").WithLocation(10, 9)); } [WorkItem(3923, "https://github.com/dotnet/roslyn/issues/3923")] [Fact] public void ExpressionTreeLocalFunctionUsage_01() { var source = @" using System; using System.Linq.Expressions; class Program { static void Main() { T Id<T>(T x) { return x; } Expression<Func<T>> Local<T>(Expression<Func<T>> f) { return f; } Console.Write(Local(() => Id(2))); Console.Write(Local<Func<int, int>>(() => Id)); Console.Write(Local(() => new Func<int, int>(Id))); Console.Write(Local(() => nameof(Id))); } } "; VerifyDiagnostics(source, // (16,35): error CS8096: An expression tree may not contain a reference to a local function // Console.Write(Local(() => Id(2))); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsLocalFunction, "Id(2)").WithLocation(16, 35), // (17,51): error CS8096: An expression tree may not contain a reference to a local function // Console.Write(Local<Func<int, int>>(() => Id)); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsLocalFunction, "Id").WithLocation(17, 51), // (18,35): error CS8096: An expression tree may not contain a reference to a local function // Console.Write(Local(() => new Func<int, int>(Id))); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsLocalFunction, "Id").WithLocation(18, 54) ); } [Fact] public void ExpressionTreeLocalFunctionUsage_02() { var source = @" using System; using System.Linq.Expressions; class Program { static void Main() { static T Id<T>(T x) { return x; } static Expression<Func<T>> Local<T>(Expression<Func<T>> f) { return f; } Console.Write(Local(() => Id(2))); Console.Write(Local<Func<int, int>>(() => Id)); Console.Write(Local(() => new Func<int, int>(Id))); Console.Write(Local(() => nameof(Id))); } } "; VerifyDiagnostics(source, // (16,35): error CS8096: An expression tree may not contain a reference to a local function // Console.Write(Local(() => Id(2))); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsLocalFunction, "Id(2)").WithLocation(16, 35), // (17,51): error CS8096: An expression tree may not contain a reference to a local function // Console.Write(Local<Func<int, int>>(() => Id)); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsLocalFunction, "Id").WithLocation(17, 51), // (18,35): error CS8096: An expression tree may not contain a reference to a local function // Console.Write(Local(() => new Func<int, int>(Id))); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsLocalFunction, "Id").WithLocation(18, 54) ); } [Fact] public void ExpressionTreeLocalFunctionInside() { var source = @" using System; using System.Linq.Expressions; class Program { static void Main() { Expression<Func<int, int>> f = x => { int Local(int y) => y; return Local(x); }; Console.Write(f); } } "; VerifyDiagnostics(source, // (8,40): error CS0834: A lambda expression with a statement body cannot be converted to an expression tree // Expression<Func<int, int>> f = x => Diagnostic(ErrorCode.ERR_StatementLambdaToExpressionTree, @"x => { int Local(int y) => y; return Local(x); }").WithLocation(8, 40), // (11,20): error CS8096: An expression tree may not contain a local function or a reference to a local function // return Local(x); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsLocalFunction, "Local(x)").WithLocation(11, 20) ); } [Fact] public void BadScoping() { var source = @" using System; class Program { static void Main(string[] args) { if (true) { void Local() { Console.WriteLine(2); } Local(); } Local(); Local2(); void Local2() { Console.WriteLine(2); } } } "; VerifyDiagnostics(source, // (16,9): error CS0103: The name 'Local' does not exist in the current context // Local(); Diagnostic(ErrorCode.ERR_NameNotInContext, "Local").WithArguments("Local").WithLocation(16, 9) ); } [Fact] public void NameConflictDuplicate() { var source = @" class Program { static void Main(string[] args) { void Duplicate() { } void Duplicate() { } Duplicate(); } } "; VerifyDiagnostics(source, // (7,14): error CS0128: A local variable named 'Duplicate' is already defined in this scope // void Duplicate() { } Diagnostic(ErrorCode.ERR_LocalDuplicate, "Duplicate").WithArguments("Duplicate").WithLocation(7, 14), // (7,14): warning CS8321: The local function 'Duplicate' is declared but never used // void Duplicate() { } Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Duplicate").WithArguments("Duplicate").WithLocation(7, 14) ); } [Fact] public void NameConflictParameter() { var source = @" class Program { static void Main(string[] args) { int x = 2; void Param(int x) { } Param(x); } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics( // (7,24): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // void Param(int x) { } Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(7, 24)); comp = CreateCompilation(source, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); } [Fact] public void NameConflictTypeParameter() { var source = @" class Program { static void Main(string[] args) { int T; void Generic<T>() { } Generic<int>(); } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics( // (7,22): error CS0136: A local or parameter named 'T' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // void Generic<T>() { } Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "T").WithArguments("T").WithLocation(7, 22), // (6,13): warning CS0168: The variable 'T' is declared but never used // int T; Diagnostic(ErrorCode.WRN_UnreferencedVar, "T").WithArguments("T").WithLocation(6, 13)); comp = CreateCompilation(source, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (6,13): warning CS0168: The variable 'T' is declared but never used // int T; Diagnostic(ErrorCode.WRN_UnreferencedVar, "T").WithArguments("T").WithLocation(6, 13)); } [Fact] public void NameConflictNestedTypeParameter() { var source = @" class Program { static void Main(string[] args) { T Outer<T>() { T Inner<T>() { return default(T); } return Inner<T>(); } System.Console.Write(Outer<int>()); } } "; VerifyDiagnostics(source, // (8,21): warning CS8387: Type parameter 'T' has the same name as the type parameter from outer method 'Outer<T>()' // T Inner<T>() Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterMethodTypeParameter, "T").WithArguments("T", "Outer<T>()").WithLocation(8, 21) ); } [Fact] public void NameConflictLocalVarFirst() { var source = @" class Program { static void Main(string[] args) { int Conflict; void Conflict() { } } } "; VerifyDiagnostics(source, // (7,14): error CS0128: A local variable named 'Conflict' is already defined in this scope // void Conflict() { } Diagnostic(ErrorCode.ERR_LocalDuplicate, "Conflict").WithArguments("Conflict").WithLocation(7, 14), // (6,13): warning CS0168: The variable 'Conflict' is declared but never used // int Conflict; Diagnostic(ErrorCode.WRN_UnreferencedVar, "Conflict").WithArguments("Conflict").WithLocation(6, 13), // (7,14): warning CS8321: The local function 'Conflict' is declared but never used // void Conflict() { } Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Conflict").WithArguments("Conflict").WithLocation(7, 14) ); } [Fact] public void NameConflictLocalVarLast() { var source = @" class Program { static void Main(string[] args) { void Conflict() { } int Conflict; } } "; // TODO: This is strange. Probably has to do with the fact that local variables are preferred over functions. VerifyDiagnostics(source, // (6,14): error CS0136: A local or parameter named 'Conflict' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // void Conflict() { } Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "Conflict").WithArguments("Conflict").WithLocation(6, 14), // (7,13): warning CS0168: The variable 'Conflict' is declared but never used // int Conflict; Diagnostic(ErrorCode.WRN_UnreferencedVar, "Conflict").WithArguments("Conflict").WithLocation(7, 13), // (6,14): warning CS8321: The local function 'Conflict' is declared but never used // void Conflict() { } Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Conflict").WithArguments("Conflict").WithLocation(6, 14) ); } [Fact] public void BadUnsafeNoKeyword() { var source = @" using System; class Program { static void A() { void Local() { int x = 2; Console.WriteLine(*&x); } Local(); } static void Main(string[] args) { A(); } } "; VerifyDiagnostics(source, // (11,32): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // Console.WriteLine(*&x); Diagnostic(ErrorCode.ERR_UnsafeNeeded, "&x").WithLocation(11, 32) ); } [Fact] public void BadUnsafeKeywordDoesntApply() { var source = @" using System; class Program { static unsafe void B() { void Local() { int x = 2; Console.WriteLine(*&x); } Local(); } static void Main(string[] args) { B(); } } "; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe.WithAllowUnsafe(true)); comp.VerifyDiagnostics(); } [Fact] public void BadEmptyBody() { var source = @" class Program { static void Main(string[] args) { void Local(int x); Local(2); } }"; VerifyDiagnostics(source, // (6,14): error CS8112: 'Local(int)' is a local function and must therefore always have a body. // void Local(int x); Diagnostic(ErrorCode.ERR_LocalFunctionMissingBody, "Local").WithArguments("Local(int)").WithLocation(6, 14) ); } [Fact] public void BadGotoInto() { var source = @" using System; class Program { static void Main(string[] args) { goto A; void Local() { A: Console.Write(2); } Local(); } }"; VerifyDiagnostics(source, // (8,14): error CS0159: No such label 'A' within the scope of the goto statement // goto A; Diagnostic(ErrorCode.ERR_LabelNotFound, "A").WithArguments("A").WithLocation(8, 14), // (11,9): warning CS0164: This label has not been referenced // A: Console.Write(2); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "A").WithLocation(11, 9) ); } [Fact] public void BadGotoOutOf() { var source = @" class Program { static void Main(string[] args) { void Local() { goto A; } A: Local(); } }"; VerifyDiagnostics(source, // (8,13): error CS0159: No such label 'A' within the scope of the goto statement // goto A; Diagnostic(ErrorCode.ERR_LabelNotFound, "goto").WithArguments("A").WithLocation(8, 13) ); } [Fact] public void BadDefiniteAssignmentCall() { var source = @" using System; class Program { static void A() { goto Label; int x = 2; void Local() { Console.Write(x); } Label: Local(); } static void Main(string[] args) { A(); } }"; VerifyDiagnostics(source, // (9,9): warning CS0162: Unreachable code detected // int x = 2; Diagnostic(ErrorCode.WRN_UnreachableCode, "int").WithLocation(9, 9), // (15,9): error CS0165: Use of unassigned local variable 'x' // Local(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Local()").WithArguments("x").WithLocation(15, 9) ); } [Fact] public void BadDefiniteAssignmentDelegateConversion() { var source = @" using System; class Program { static void A() { goto Label; int x = 2; void Local() { Console.Write(x); } Label: Action goo = Local; } static void Main(string[] args) { A(); } }"; VerifyDiagnostics(source, // (9,9): warning CS0162: Unreachable code detected // int x = 2; Diagnostic(ErrorCode.WRN_UnreachableCode, "int").WithLocation(9, 9), // (15,22): error CS0165: Use of unassigned local variable 'x' // Action goo = Local; Diagnostic(ErrorCode.ERR_UseDefViolation, "Local").WithArguments("x").WithLocation(15, 22) ); } [Fact] public void BadDefiniteAssignmentDelegateConstruction() { var source = @" using System; class Program { static void A() { goto Label; int x = 2; void Local() { Console.Write(x); } Label: var bar = new Action(Local); } static void Main(string[] args) { A(); } }"; VerifyDiagnostics(source, // (9,9): warning CS0162: Unreachable code detected // int x = 2; Diagnostic(ErrorCode.WRN_UnreachableCode, "int").WithLocation(9, 9), // (15,19): error CS0165: Use of unassigned local variable 'x' // var bar = new Action(Local); Diagnostic(ErrorCode.ERR_UseDefViolation, "new Action(Local)").WithArguments("x").WithLocation(15, 19) ); } [Fact] public void BadNotUsed() { var source = @" class Program { static void A() { void Local() { } } static void Main(string[] args) { A(); } }"; VerifyDiagnostics(source, // (6,14): warning CS8321: The local function 'Local' is declared but never used // void Local() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local").WithArguments("Local").WithLocation(6, 14) ); } [Fact] public void BadNotUsedSwitch() { var source = @" class Program { static void A() { switch (0) { case 0: void Local() { } break; } } static void Main(string[] args) { A(); } }"; VerifyDiagnostics(source, // (9,18): warning CS8321: The local function 'Local' is declared but never used // void Local() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local").WithArguments("Local").WithLocation(9, 18) ); } [Fact] public void BadByRefClosure() { var source = @" using System; class Program { static void A(ref int x) { void Local() { Console.WriteLine(x); } Local(); } static void Main() { } }"; VerifyDiagnostics(source, // (10,31): error CS1628: Cannot use ref or out parameter 'x' inside an anonymous method, lambda expression, query expression, or local function // Console.WriteLine(x); Diagnostic(ErrorCode.ERR_AnonDelegateCantUse, "x").WithArguments("x").WithLocation(10, 31) ); } [Fact] public void BadInClosure() { var source = @" using System; class Program { static void A(in int x) { void Local() { Console.WriteLine(x); } Local(); } static void Main() { } }"; VerifyDiagnostics(source, // (10,31): error CS1628: Cannot use ref, out, or in parameter 'x' inside an anonymous method, lambda expression, query expression, or local function // Console.WriteLine(x); Diagnostic(ErrorCode.ERR_AnonDelegateCantUse, "x").WithArguments("x").WithLocation(10, 31) ); } [Fact] public void BadArglistUse() { var source = @" using System; class Program { static void A() { void Local() { Console.WriteLine(__arglist); } Local(); } static void B(__arglist) { void Local() { Console.WriteLine(__arglist); } Local(); } static void C() // C and D produce different errors { void Local(__arglist) { Console.WriteLine(__arglist); } Local(__arglist()); } static void D(__arglist) { void Local(__arglist) { Console.WriteLine(__arglist); } Local(__arglist()); } static void Main() { } } "; VerifyDiagnostics(source, // (10,31): error CS0190: The __arglist construct is valid only within a variable argument method // Console.WriteLine(__arglist); Diagnostic(ErrorCode.ERR_ArgsInvalid, "__arglist").WithLocation(10, 31), // (18,31): error CS4013: Instance of type 'RuntimeArgumentHandle' cannot be used inside an anonymous function, query expression, iterator block or async method // Console.WriteLine(__arglist); Diagnostic(ErrorCode.ERR_SpecialByRefInLambda, "__arglist").WithArguments("System.RuntimeArgumentHandle").WithLocation(18, 31), // (24,20): error CS1669: __arglist is not valid in this context // void Local(__arglist) Diagnostic(ErrorCode.ERR_IllegalVarArgs, "__arglist").WithLocation(24, 20), // (26,31): error CS0190: The __arglist construct is valid only within a variable argument method // Console.WriteLine(__arglist); Diagnostic(ErrorCode.ERR_ArgsInvalid, "__arglist").WithLocation(26, 31), // (32,20): error CS1669: __arglist is not valid in this context // void Local(__arglist) Diagnostic(ErrorCode.ERR_IllegalVarArgs, "__arglist").WithLocation(32, 20), // (34,31): error CS4013: Instance of type 'RuntimeArgumentHandle' cannot be used inside an anonymous function, query expression, iterator block or async method // Console.WriteLine(__arglist); Diagnostic(ErrorCode.ERR_SpecialByRefInLambda, "__arglist").WithArguments("System.RuntimeArgumentHandle").WithLocation(34, 31) ); } [Fact] public void BadClosureStaticRefInstance() { var source = @" using System; class Program { int _a = 0; static void A() { void Local() { Console.WriteLine(_a); } Local(); } static void Main() { } } "; VerifyDiagnostics(source, // (11,31): error CS0120: An object reference is required for the non-static field, method, or property 'Program._a' // Console.WriteLine(_a); Diagnostic(ErrorCode.ERR_ObjectRequired, "_a").WithArguments("Program._a").WithLocation(11, 31) ); } [Fact] public void BadRefIterator() { var source = @" using System.Collections.Generic; class Program { static void Main(string[] args) { IEnumerable<int> RefEnumerable(ref int x) { yield return x; } int y = 0; RefEnumerable(ref y); } } "; VerifyDiagnostics(source, // (8,48): error CS1623: Iterators cannot have ref, in or out parameters // IEnumerable<int> RefEnumerable(ref int x) Diagnostic(ErrorCode.ERR_BadIteratorArgType, "x").WithLocation(8, 48) ); } [Fact] public void BadRefAsync() { var source = @" using System; using System.Threading.Tasks; class Program { static void Main(string[] args) { async Task<int> RefAsync(ref int x) { return await Task.FromResult(x); } int y = 2; Console.Write(RefAsync(ref y).Result); } } "; VerifyDiagnostics(source, // (9,42): error CS1988: Async methods cannot have ref, in or out parameters // async Task<int> RefAsync(ref int x) Diagnostic(ErrorCode.ERR_BadAsyncArgType, "x").WithLocation(9, 42) ); } [Fact] public void Extension_01() { var source = @" using System; class Program { static void Main(string[] args) { int Local(this int x) { return x; } Console.WriteLine(Local(2)); } } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (8,13): error CS1106: Extension method must be defined in a non-generic static class // int Local(this int x) Diagnostic(ErrorCode.ERR_BadExtensionAgg, "Local").WithLocation(8, 13) ); } [Fact] public void Extension_02() { var source = @"#pragma warning disable 8321 static class E { static void M() { void F1(this string s) { } static void F2(this string s) { } } }"; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (6,14): error CS1106: Extension method must be defined in a non-generic static class // void F1(this string s) { } Diagnostic(ErrorCode.ERR_BadExtensionAgg, "F1").WithLocation(6, 14), // (7,21): error CS1106: Extension method must be defined in a non-generic static class // static void F2(this string s) { } Diagnostic(ErrorCode.ERR_BadExtensionAgg, "F2").WithLocation(7, 21)); } [Fact] public void BadModifiers() { var source = @" class Program { static void Main(string[] args) { const void LocalConst() { } static void LocalStatic() { } readonly void LocalReadonly() { } volatile void LocalVolatile() { } LocalConst(); LocalStatic(); LocalReadonly(); LocalVolatile(); } } "; var baseExpected = new[] { // (6,9): error CS0106: The modifier 'const' is not valid for this item // const void LocalConst() Diagnostic(ErrorCode.ERR_BadMemberFlag, "const").WithArguments("const").WithLocation(6, 9), // (12,9): error CS0106: The modifier 'readonly' is not valid for this item // readonly void LocalReadonly() Diagnostic(ErrorCode.ERR_BadMemberFlag, "readonly").WithArguments("readonly").WithLocation(12, 9), // (15,9): error CS0106: The modifier 'volatile' is not valid for this item // volatile void LocalVolatile() Diagnostic(ErrorCode.ERR_BadMemberFlag, "volatile").WithArguments("volatile").WithLocation(15, 9) }; var extra = new[] { // (9,9): error CS8652: The feature 'static local functions' is not available in C# 7.3. Please use language version 8.0 or greater. // static void LocalStatic() Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "static").WithArguments("static local functions", "8.0").WithLocation(9, 9), }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics( baseExpected.Concat(extra).ToArray()); comp = CreateCompilation(source, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(baseExpected); comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(baseExpected); } [Fact] public void ArglistIterator() { var source = @" using System; using System.Collections.Generic; class Program { static void Main(string[] args) { IEnumerable<int> Local(__arglist) { yield return 2; } Console.WriteLine(string.Join("","", Local(__arglist()))); } } "; VerifyDiagnostics(source, // (9,26): error CS1636: __arglist is not allowed in the parameter list of iterators // IEnumerable<int> Local(__arglist) Diagnostic(ErrorCode.ERR_VarargsIterator, "Local").WithLocation(9, 26), // (9,32): error CS1669: __arglist is not valid in this context // IEnumerable<int> Local(__arglist) Diagnostic(ErrorCode.ERR_IllegalVarArgs, "__arglist").WithLocation(9, 32)); } [Fact] public void ForwardReference() { var source = @" using System; class Program { static void Main(string[] args) { Console.WriteLine(Local()); int Local() => 2; } } "; CompileAndVerify(source, expectedOutput: "2"); } [Fact] public void ForwardReferenceCapture() { var source = @" using System; class Program { static void Main(string[] args) { int x = 2; Console.WriteLine(Local()); int Local() => x; } } "; CompileAndVerify(source, expectedOutput: "2"); } [Fact] public void ForwardRefInLocalFunc() { var source = @" using System; class Program { static void Main(string[] args) { int x = 2; Console.WriteLine(Local()); int Local() { x = 3; return Local2(); } int Local2() => x; } } "; CompileAndVerify(source, expectedOutput: "3"); } [Fact] public void LocalFuncMutualRecursion() { var source = @" using System; class Program { static void Main(string[] args) { int x = 5; int y = 0; Console.WriteLine(Local1()); int Local1() { x -= 1; return Local2(y++); } int Local2(int z) { if (x == 0) { return z; } else { return Local1(); } } } } "; CompileAndVerify(source, expectedOutput: "4"); } [Fact] public void OtherSwitchBlock() { var source = @" using System; class Program { static void Main(string[] args) { var x = int.Parse(Console.ReadLine()); switch (x) { case 0: void Local() { } break; default: Local(); break; } } } "; VerifyDiagnostics(source); } [Fact] public void NoOperator() { var source = @" class Program { static void Main(string[] args) { Program operator +(Program left, Program right) { return left; } } } "; VerifyDiagnostics(source, // (6,17): error CS1002: ; expected // Program operator +(Program left, Program right) Diagnostic(ErrorCode.ERR_SemicolonExpected, "operator").WithLocation(6, 17), // (6,17): error CS1513: } expected // Program operator +(Program left, Program right) Diagnostic(ErrorCode.ERR_RbraceExpected, "operator").WithLocation(6, 17), // (6,56): error CS1002: ; expected // Program operator +(Program left, Program right) Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(6, 56), // (6,9): error CS0119: 'Program' is a type, which is not valid in the given context // Program operator +(Program left, Program right) Diagnostic(ErrorCode.ERR_BadSKunknown, "Program").WithArguments("Program", "type").WithLocation(6, 9), // (6,28): error CS8185: A declaration is not allowed in this context. // Program operator +(Program left, Program right) Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "Program left").WithLocation(6, 28), // (6,42): error CS8185: A declaration is not allowed in this context. // Program operator +(Program left, Program right) Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "Program right").WithLocation(6, 42), // (6,27): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported // Program operator +(Program left, Program right) Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(Program left, Program right)").WithArguments("System.ValueTuple`2").WithLocation(6, 27), // (8,13): error CS0127: Since 'Program.Main(string[])' returns void, a return keyword must not be followed by an object expression // return left; Diagnostic(ErrorCode.ERR_RetNoObjectRequired, "return").WithArguments("Program.Main(string[])").WithLocation(8, 13), // (6,28): error CS0165: Use of unassigned local variable 'left' // Program operator +(Program left, Program right) Diagnostic(ErrorCode.ERR_UseDefViolation, "Program left").WithArguments("left").WithLocation(6, 28), // (6,42): error CS0165: Use of unassigned local variable 'right' // Program operator +(Program left, Program right) Diagnostic(ErrorCode.ERR_UseDefViolation, "Program right").WithArguments("right").WithLocation(6, 42) ); } [Fact] public void NoProperty() { var source = @" class Program { static void Main(string[] args) { int Goo { get { return 2; } } int Bar => 2; } } "; VerifyDiagnostics(source, // (6,16): error CS1002: ; expected // int Goo Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(6, 16), // (8,16): error CS1002: ; expected // get Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(8, 16), // (13,17): error CS1003: Syntax error, ',' expected // int Bar => 2; Diagnostic(ErrorCode.ERR_SyntaxError, "=>").WithArguments(",", "=>").WithLocation(13, 17), // (13,20): error CS1002: ; expected // int Bar => 2; Diagnostic(ErrorCode.ERR_SemicolonExpected, "2").WithLocation(13, 20), // (8,13): error CS0103: The name 'get' does not exist in the current context // get Diagnostic(ErrorCode.ERR_NameNotInContext, "get").WithArguments("get").WithLocation(8, 13), // (10,17): error CS0127: Since 'Program.Main(string[])' returns void, a return keyword must not be followed by an object expression // return 2; Diagnostic(ErrorCode.ERR_RetNoObjectRequired, "return").WithArguments("Program.Main(string[])").WithLocation(10, 17), // (13,20): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // int Bar => 2; Diagnostic(ErrorCode.ERR_IllegalStatement, "2").WithLocation(13, 20), // (13,9): warning CS0162: Unreachable code detected // int Bar => 2; Diagnostic(ErrorCode.WRN_UnreachableCode, "int").WithLocation(13, 9), // (6,13): warning CS0168: The variable 'Goo' is declared but never used // int Goo Diagnostic(ErrorCode.WRN_UnreferencedVar, "Goo").WithArguments("Goo").WithLocation(6, 13), // (13,13): warning CS0168: The variable 'Bar' is declared but never used // int Bar => 2; Diagnostic(ErrorCode.WRN_UnreferencedVar, "Bar").WithArguments("Bar").WithLocation(13, 13) ); } [Fact] public void NoFeatureSwitch() { var source = @" class Program { static void Main(string[] args) { void Local() { } Local(); } } "; var option = TestOptions.ReleaseExe; CreateCompilation(source, options: option, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)).VerifyDiagnostics( // (6,14): error CS8059: Feature 'local functions' is not available in C# 6. Please use language version 7.0 or greater. // void Local() { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "Local").WithArguments("local functions", "7.0").WithLocation(6, 14) ); } [Fact, WorkItem(10521, "https://github.com/dotnet/roslyn/issues/10521")] public void LocalFunctionInIf() { var source = @" class Program { static void Main(string[] args) { if () // typing at this point int Add(int x, int y) => x + y; } } "; VerifyDiagnostics(source, // (6,13): error CS1525: Invalid expression term ')' // if () // typing at this point Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(6, 13), // (7,9): error CS1023: Embedded statement cannot be a declaration or labeled statement // int Add(int x, int y) => x + y; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "int Add(int x, int y) => x + y;").WithLocation(7, 9), // (7,13): warning CS8321: The local function 'Add' is declared but never used // int Add(int x, int y) => x + y; Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Add").WithArguments("Add").WithLocation(7, 13) ); } [Fact, WorkItem(10521, "https://github.com/dotnet/roslyn/issues/10521")] public void LabeledLocalFunctionInIf() { var source = @" class Program { static void Main(string[] args) { if () // typing at this point a: int Add(int x, int y) => x + y; } } "; VerifyDiagnostics(source, // (6,13): error CS1525: Invalid expression term ')' // if () // typing at this point Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(6, 13), // (7,1): error CS1023: Embedded statement cannot be a declaration or labeled statement // a: int Add(int x, int y) => x + y; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "a: int Add(int x, int y) => x + y;").WithLocation(7, 1), // (7,1): warning CS0164: This label has not been referenced // a: int Add(int x, int y) => x + y; Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(7, 1), // (7,13): warning CS8321: The local function 'Add' is declared but never used // a: int Add(int x, int y) => x + y; Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Add").WithArguments("Add").WithLocation(7, 13) ); } [CompilerTrait(CompilerFeature.LocalFunctions, CompilerFeature.Var)] public sealed class VarTests : LocalFunctionsTestBase { [Fact] public void IllegalAsReturn() { var source = @" using System; class Program { static void Main() { var f() => 42; Console.WriteLine(f()); } }"; var comp = CreateCompilationWithMscorlib45(source, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (7,9): error CS0825: The contextual keyword 'var' may only appear within a local variable declaration or in script code // var f() => 42; Diagnostic(ErrorCode.ERR_TypeVarNotFound, "var").WithLocation(7, 9)); } [Fact] public void RealTypeAsReturn() { var source = @" using System; class var { public override string ToString() => ""dog""; } class Program { static void Main() { var f() => new var(); Console.WriteLine(f()); } }"; CompileAndVerify( source, parseOptions: DefaultParseOptions, expectedOutput: "dog"); } [Fact] public void RealTypeParameterAsReturn() { var source = @" using System; class test { public override string ToString() => ""dog""; } class Program { static void Test<var>(var x) { var f() => x; Console.WriteLine(f()); } static void Main() { Test(new test()); } }"; CompileAndVerify( source, parseOptions: DefaultParseOptions, expectedOutput: "dog"); } [Fact] public void IdentifierAndTypeNamedVar() { var source = @" using System; class var { public override string ToString() => ""dog""; } class Program { static void Main() { int var = 42; var f() => new var(); Console.WriteLine($""{f()}-{var}""); } }"; CompileAndVerify( source, parseOptions: DefaultParseOptions, expectedOutput: "dog-42"); } } [CompilerTrait(CompilerFeature.LocalFunctions, CompilerFeature.Async)] public sealed class AsyncTests : LocalFunctionsTestBase { [Fact] public void RealTypeAsReturn() { var source = @" using System; class async { public override string ToString() => ""dog""; } class Program { static void Main() { async f() => new async(); Console.WriteLine(f()); } }"; CompileAndVerify( source, parseOptions: DefaultParseOptions, expectedOutput: "dog"); } [Fact] public void RealTypeParameterAsReturn() { var source = @" using System; class test { public override string ToString() => ""dog""; } class Program { static void Test<async>(async x) { async f() => x; Console.WriteLine(f()); } static void Main() { Test(new test()); } }"; CompileAndVerify( source, parseOptions: DefaultParseOptions, expectedOutput: "dog"); } [Fact] public void ManyMeaningsType() { var source = @" using System; using System.Threading; using System.Threading.Tasks; class async { public override string ToString() => ""async""; } class Program { static void Main() { async Task<async> Test(Task<async> t) { async local = await t; Console.WriteLine(local); return local; } Test(Task.FromResult<async>(new async())).Wait(); } }"; var comp = CreateCompilationWithMscorlib46(source, parseOptions: DefaultParseOptions, options: TestOptions.DebugExe); CompileAndVerify( comp, expectedOutput: "async"); } } [Fact] [WorkItem(12467, "https://github.com/dotnet/roslyn/issues/12467")] public void ParamUnassigned_01() { var src = @" class C { public void M1() { void TakeOutParam1(out int x) { } int y; TakeOutParam1(out y); } void TakeOutParam2(out int x) { } }"; VerifyDiagnostics(src, // (6,14): error CS0177: The out parameter 'x' must be assigned to before control leaves the current method // void TakeOutParam1(out int x) Diagnostic(ErrorCode.ERR_ParamUnassigned, "TakeOutParam1").WithArguments("x").WithLocation(6, 14), // (14,14): error CS0177: The out parameter 'x' must be assigned to before control leaves the current method // void TakeOutParam2(out int x) Diagnostic(ErrorCode.ERR_ParamUnassigned, "TakeOutParam2").WithArguments("x").WithLocation(14, 14) ); } [Fact] [WorkItem(12467, "https://github.com/dotnet/roslyn/issues/12467")] public void ParamUnassigned_02() { var src = @" class C { public void M1() { void TakeOutParam1(out int x) { return; // 1 } int y; TakeOutParam1(out y); } void TakeOutParam2(out int x) { return; // 2 } }"; VerifyDiagnostics(src, // (8,13): error CS0177: The out parameter 'x' must be assigned to before control leaves the current method // return; // 1 Diagnostic(ErrorCode.ERR_ParamUnassigned, "return;").WithArguments("x").WithLocation(8, 13), // (17,13): error CS0177: The out parameter 'x' must be assigned to before control leaves the current method // return; // 2 Diagnostic(ErrorCode.ERR_ParamUnassigned, "return;").WithArguments("x").WithLocation(17, 13) ); } [Fact] [WorkItem(12467, "https://github.com/dotnet/roslyn/issues/12467")] public void ParamUnassigned_03() { var src = @" class C { public void M1() { int TakeOutParam1(out int x) { } int y; TakeOutParam1(out y); } int TakeOutParam2(out int x) { } }"; VerifyDiagnostics(src, // (6,13): error CS0161: 'TakeOutParam1(out int)': not all code paths return a value // int TakeOutParam1(out int x) Diagnostic(ErrorCode.ERR_ReturnExpected, "TakeOutParam1").WithArguments("TakeOutParam1(out int)").WithLocation(6, 13), // (6,13): error CS0177: The out parameter 'x' must be assigned to before control leaves the current method // int TakeOutParam1(out int x) Diagnostic(ErrorCode.ERR_ParamUnassigned, "TakeOutParam1").WithArguments("x").WithLocation(6, 13), // (14,13): error CS0177: The out parameter 'x' must be assigned to before control leaves the current method // int TakeOutParam2(out int x) Diagnostic(ErrorCode.ERR_ParamUnassigned, "TakeOutParam2").WithArguments("x").WithLocation(14, 13), // (14,13): error CS0161: 'C.TakeOutParam2(out int)': not all code paths return a value // int TakeOutParam2(out int x) Diagnostic(ErrorCode.ERR_ReturnExpected, "TakeOutParam2").WithArguments("C.TakeOutParam2(out int)").WithLocation(14, 13) ); } [Fact] [WorkItem(12467, "https://github.com/dotnet/roslyn/issues/12467")] public void ParamUnassigned_04() { var src = @" class C { public void M1() { int TakeOutParam1(out int x) { return 1; } int y; TakeOutParam1(out y); } int TakeOutParam2(out int x) { return 2; } }"; VerifyDiagnostics(src, // (8,13): error CS0177: The out parameter 'x' must be assigned to before control leaves the current method // return 1; Diagnostic(ErrorCode.ERR_ParamUnassigned, "return 1;").WithArguments("x").WithLocation(8, 13), // (17,13): error CS0177: The out parameter 'x' must be assigned to before control leaves the current method // return 2; Diagnostic(ErrorCode.ERR_ParamUnassigned, "return 2;").WithArguments("x").WithLocation(17, 13) ); } [Fact] [WorkItem(49500, "https://github.com/dotnet/roslyn/issues/49500")] public void OutParam_Extern_01() { var src = @" using System.Runtime.InteropServices; class C { void M() { int x; local(out x); x.ToString(); [DllImport(""a"")] static extern void local(out int x); } [DllImport(""a"")] static extern void Method(out int x); }"; VerifyDiagnostics(src); } [Fact] [WorkItem(49500, "https://github.com/dotnet/roslyn/issues/49500")] public void OutParam_Extern_02() { var src = @" using System.Runtime.InteropServices; class C { void M() { local1(out _); local2(out _); local3(out _); [DllImport(""a"")] static extern void local1(out int x) { } // 1 static void local2(out int x) { } // 2 static void local3(out int x); // 3, 4 } [DllImport(""a"")] static extern void Method(out int x); }"; VerifyDiagnostics(src, // (13,28): error CS0179: 'local1(out int)' cannot be extern and declare a body // static extern void local1(out int x) { } // 1 Diagnostic(ErrorCode.ERR_ExternHasBody, "local1").WithArguments("local1(out int)").WithLocation(13, 28), // (15,21): error CS0177: The out parameter 'x' must be assigned to before control leaves the current method // static void local2(out int x) { } // 2 Diagnostic(ErrorCode.ERR_ParamUnassigned, "local2").WithArguments("x").WithLocation(15, 21), // (17,21): error CS8112: Local function 'local3(out int)' must declare a body because it is not marked 'static extern'. // static void local3(out int x); // 3, 4 Diagnostic(ErrorCode.ERR_LocalFunctionMissingBody, "local3").WithArguments("local3(out int)").WithLocation(17, 21), // (17,21): error CS0177: The out parameter 'x' must be assigned to before control leaves the current method // static void local3(out int x); // 3, 4 Diagnostic(ErrorCode.ERR_ParamUnassigned, "local3").WithArguments("x").WithLocation(17, 21)); } [Fact] [WorkItem(13172, "https://github.com/dotnet/roslyn/issues/13172")] public void InheritUnsafeContext() { var comp = CreateCompilationWithMscorlib46(@" using System; using System.Threading.Tasks; class C { public void M1() { async Task<IntPtr> Local() { await Task.Delay(0); return (IntPtr)(void*)null; } var _ = Local(); } public void M2() { unsafe { async Task<IntPtr> Local() { await Task.Delay(1); return (IntPtr)(void*)null; } var _ = Local(); } } public unsafe void M3() { async Task<IntPtr> Local() { await Task.Delay(2); return (IntPtr)(void*)null; } var _ = Local(); } } unsafe class D { int* p = null; public void M() { async Task<IntPtr> Local() { await Task.Delay(3); return (IntPtr)p; } var _ = Local(); } public unsafe void M2() { unsafe { async Task<IntPtr> Local() { await Task.Delay(4); return (IntPtr)(void*)null; } var _ = Local(); } } }", options: TestOptions.UnsafeDebugDll); comp.VerifyDiagnostics( // (11,29): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // return (IntPtr)(void*)null; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "void*").WithLocation(11, 29), // (11,28): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // return (IntPtr)(void*)null; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "(void*)null").WithLocation(11, 28), // (47,13): error CS4004: Cannot await in an unsafe context // await Task.Delay(3); Diagnostic(ErrorCode.ERR_AwaitInUnsafeContext, "await Task.Delay(3)").WithLocation(47, 13), // (22,17): error CS4004: Cannot await in an unsafe context // await Task.Delay(1); Diagnostic(ErrorCode.ERR_AwaitInUnsafeContext, "await Task.Delay(1)").WithLocation(22, 17), // (59,17): error CS4004: Cannot await in an unsafe context // await Task.Delay(4); Diagnostic(ErrorCode.ERR_AwaitInUnsafeContext, "await Task.Delay(4)").WithLocation(59, 17), // (33,13): error CS4004: Cannot await in an unsafe context // await Task.Delay(2); Diagnostic(ErrorCode.ERR_AwaitInUnsafeContext, "await Task.Delay(2)").WithLocation(33, 13)); } [Fact, WorkItem(16167, "https://github.com/dotnet/roslyn/issues/16167")] public void DeclarationInLocalFunctionParameterDefault() { var text = @" class C { public static void Main(int arg) { void Local1(bool b = M(arg is int z1, z1), int s1 = z1) {} void Local2(bool b = M(M(out int z2), z2), int s2 = z2) {} void Local3(bool b = M(M((int z3, int a2) = (1, 2)), z3), int a3 = z3) {} void Local4(bool b = M(arg is var z4, z4), int s1 = z4) {} void Local5(bool b = M(M(out var z5), z5), int s2 = z5) {} void Local6(bool b = M(M((var z6, int a2) = (1, 2)), z6), int a3 = z6) {} int t = z1 + z2 + z3 + z4 + z5 + z6; } static bool M(out int z) // needed to infer type of z5 { z = 1; return true; } static bool M(params object[] args) => true; } namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { Item1 = item1; Item2 = item2; } } } "; // the scope of an expression variable introduced in the default expression // of a local function parameter is that default expression. var compilation = CreateCompilationWithMscorlib45(text); compilation.VerifyDiagnostics( // (6,30): error CS1736: Default parameter value for 'b' must be a compile-time constant // void Local1(bool b = M(arg is int z1, z1), int s1 = z1) {} Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "M(arg is int z1, z1)").WithArguments("b").WithLocation(6, 30), // (6,61): error CS0103: The name 'z1' does not exist in the current context // void Local1(bool b = M(arg is int z1, z1), int s1 = z1) {} Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(6, 61), // (7,30): error CS1736: Default parameter value for 'b' must be a compile-time constant // void Local2(bool b = M(M(out int z2), z2), int s2 = z2) {} Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "M(M(out int z2), z2)").WithArguments("b").WithLocation(7, 30), // (7,61): error CS0103: The name 'z2' does not exist in the current context // void Local2(bool b = M(M(out int z2), z2), int s2 = z2) {} Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(7, 61), // (8,35): error CS8185: A declaration is not allowed in this context. // void Local3(bool b = M(M((int z3, int a2) = (1, 2)), z3), int a3 = z3) {} Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int z3").WithLocation(8, 35), // (8,30): error CS1736: Default parameter value for 'b' must be a compile-time constant // void Local3(bool b = M(M((int z3, int a2) = (1, 2)), z3), int a3 = z3) {} Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "M(M((int z3, int a2) = (1, 2)), z3)").WithArguments("b").WithLocation(8, 30), // (8,76): error CS0103: The name 'z3' does not exist in the current context // void Local3(bool b = M(M((int z3, int a2) = (1, 2)), z3), int a3 = z3) {} Diagnostic(ErrorCode.ERR_NameNotInContext, "z3").WithArguments("z3").WithLocation(8, 76), // (10,30): error CS1736: Default parameter value for 'b' must be a compile-time constant // void Local4(bool b = M(arg is var z4, z4), int s1 = z4) {} Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "M(arg is var z4, z4)").WithArguments("b").WithLocation(10, 30), // (10,61): error CS0103: The name 'z4' does not exist in the current context // void Local4(bool b = M(arg is var z4, z4), int s1 = z4) {} Diagnostic(ErrorCode.ERR_NameNotInContext, "z4").WithArguments("z4").WithLocation(10, 61), // (11,30): error CS1736: Default parameter value for 'b' must be a compile-time constant // void Local5(bool b = M(M(out var z5), z5), int s2 = z5) {} Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "M(M(out var z5), z5)").WithArguments("b").WithLocation(11, 30), // (11,61): error CS0103: The name 'z5' does not exist in the current context // void Local5(bool b = M(M(out var z5), z5), int s2 = z5) {} Diagnostic(ErrorCode.ERR_NameNotInContext, "z5").WithArguments("z5").WithLocation(11, 61), // (12,35): error CS8185: A declaration is not allowed in this context. // void Local6(bool b = M(M((var z6, int a2) = (1, 2)), z6), int a3 = z6) {} Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var z6").WithLocation(12, 35), // (12,30): error CS1736: Default parameter value for 'b' must be a compile-time constant // void Local6(bool b = M(M((var z6, int a2) = (1, 2)), z6), int a3 = z6) {} Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "M(M((var z6, int a2) = (1, 2)), z6)").WithArguments("b").WithLocation(12, 30), // (12,76): error CS0103: The name 'z6' does not exist in the current context // void Local6(bool b = M(M((var z6, int a2) = (1, 2)), z6), int a3 = z6) {} Diagnostic(ErrorCode.ERR_NameNotInContext, "z6").WithArguments("z6").WithLocation(12, 76), // (14,17): error CS0103: The name 'z1' does not exist in the current context // int t = z1 + z2 + z3 + z4 + z5 + z6; Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(14, 17), // (14,22): error CS0103: The name 'z2' does not exist in the current context // int t = z1 + z2 + z3 + z4 + z5 + z6; Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(14, 22), // (14,27): error CS0103: The name 'z3' does not exist in the current context // int t = z1 + z2 + z3 + z4 + z5 + z6; Diagnostic(ErrorCode.ERR_NameNotInContext, "z3").WithArguments("z3").WithLocation(14, 27), // (14,32): error CS0103: The name 'z4' does not exist in the current context // int t = z1 + z2 + z3 + z4 + z5 + z6; Diagnostic(ErrorCode.ERR_NameNotInContext, "z4").WithArguments("z4").WithLocation(14, 32), // (14,37): error CS0103: The name 'z5' does not exist in the current context // int t = z1 + z2 + z3 + z4 + z5 + z6; Diagnostic(ErrorCode.ERR_NameNotInContext, "z5").WithArguments("z5").WithLocation(14, 37), // (14,42): error CS0103: The name 'z6' does not exist in the current context // int t = z1 + z2 + z3 + z4 + z5 + z6; Diagnostic(ErrorCode.ERR_NameNotInContext, "z6").WithArguments("z6").WithLocation(14, 42), // (6,14): warning CS8321: The local function 'Local1' is declared but never used // void Local1(bool b = M(arg is int z1, z1), int s1 = z1) {} Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local1").WithArguments("Local1").WithLocation(6, 14), // (7,14): warning CS8321: The local function 'Local2' is declared but never used // void Local2(bool b = M(M(out int z2), z2), int s2 = z2) {} Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local2").WithArguments("Local2").WithLocation(7, 14), // (8,14): warning CS8321: The local function 'Local3' is declared but never used // void Local3(bool b = M(M((int z3, int a2) = (1, 2)), z3), int a3 = z3) {} Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local3").WithArguments("Local3").WithLocation(8, 14), // (10,14): warning CS8321: The local function 'Local4' is declared but never used // void Local4(bool b = M(arg is var z4, z4), int s1 = z4) {} Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local4").WithArguments("Local4").WithLocation(10, 14), // (11,14): warning CS8321: The local function 'Local5' is declared but never used // void Local5(bool b = M(M(out var z5), z5), int s2 = z5) {} Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local5").WithArguments("Local5").WithLocation(11, 14), // (12,14): warning CS8321: The local function 'Local6' is declared but never used // void Local6(bool b = M(M((var z6, int a2) = (1, 2)), z6), int a3 = z6) {} Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local6").WithArguments("Local6").WithLocation(12, 14) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var descendents = tree.GetRoot().DescendantNodes(); for (int i = 1; i <= 6; i++) { var name = $"z{i}"; var designation = descendents.OfType<SingleVariableDesignationSyntax>().Where(d => d.Identifier.ValueText == name).Single(); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(designation); Assert.NotNull(symbol); Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString()); var refs = descendents.OfType<IdentifierNameSyntax>().Where(n => n.Identifier.ValueText == name).ToArray(); Assert.Equal(3, refs.Length); Assert.Equal(symbol, model.GetSymbolInfo(refs[0]).Symbol); Assert.Null(model.GetSymbolInfo(refs[1]).Symbol); Assert.Null(model.GetSymbolInfo(refs[2]).Symbol); } } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/16451")] public void RecursiveParameterDefault() { var text = @" class C { public static void Main(int arg) { int Local(int x = Local()) => 2; } } "; var compilation = CreateCompilationWithMscorlib45(text); compilation.VerifyDiagnostics( ); } [Fact] [WorkItem(16757, "https://github.com/dotnet/roslyn/issues/16757")] public void LocalFunctionParameterDefaultUsingConst() { var source = @" class C { public static void Main() { const int N = 2; void Local1(int n = N) { System.Console.Write(n); } Local1(); Local1(3); } } "; CompileAndVerify(source, expectedOutput: "23", sourceSymbolValidator: m => { var compilation = m.DeclaringCompilation; // See https://github.com/dotnet/roslyn/issues/16454; this should actually produce no errors compilation.VerifyDiagnostics( // (6,19): warning CS0219: The variable 'N' is assigned but its value is never used // const int N = 2; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "N").WithArguments("N").WithLocation(6, 19) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var descendents = tree.GetRoot().DescendantNodes(); var parameter = descendents.OfType<ParameterSyntax>().Single(); Assert.Equal("int n = N", parameter.ToString()); Assert.Equal("[System.Int32 n = 2]", model.GetDeclaredSymbol(parameter).ToTestDisplayString()); var name = "N"; var declarator = descendents.OfType<VariableDeclaratorSyntax>().Where(d => d.Identifier.ValueText == name).Single(); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(declarator); Assert.NotNull(symbol); Assert.Equal("System.Int32 N", symbol.ToTestDisplayString()); var refs = descendents.OfType<IdentifierNameSyntax>().Where(n => n.Identifier.ValueText == name).ToArray(); Assert.Equal(1, refs.Length); Assert.Same(symbol, model.GetSymbolInfo(refs[0]).Symbol); }); } [Fact] [WorkItem(15536, "https://github.com/dotnet/roslyn/issues/15536")] public void CallFromDifferentSwitchSection_01() { var source = @" class Program { static void Main() { Test(string.Empty); } static void Test(object o) { switch (o) { case string x: Assign(); Print(); break; case int x: void Assign() { x = 5; } void Print() => System.Console.WriteLine(x); break; } } }"; var comp = CreateCompilationWithMscorlib46(source, parseOptions: DefaultParseOptions, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: "5"); } [Fact] [WorkItem(15536, "https://github.com/dotnet/roslyn/issues/15536")] public void CallFromDifferentSwitchSection_02() { var source = @" class Program { static void Main() { Test(string.Empty); } static void Test(object o) { switch (o) { case int x: void Assign() { x = 5; } void Print() => System.Console.WriteLine(x); break; case string x: Assign(); Print(); break; } } }"; var comp = CreateCompilationWithMscorlib46(source, parseOptions: DefaultParseOptions, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: "5"); } [Fact] [WorkItem(15536, "https://github.com/dotnet/roslyn/issues/15536")] public void CallFromDifferentSwitchSection_03() { var source = @" class Program { static void Main() { Test(string.Empty); } static void Test(object o) { switch (o) { case string x: Assign(); System.Action p = Print; p(); break; case int x: void Assign() { x = 5; } void Print() => System.Console.WriteLine(x); break; } } }"; var comp = CreateCompilationWithMscorlib46(source, parseOptions: DefaultParseOptions, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: "5"); } [Fact] [WorkItem(15536, "https://github.com/dotnet/roslyn/issues/15536")] public void CallFromDifferentSwitchSection_04() { var source = @" class Program { static void Main() { Test(string.Empty); } static void Test(object o) { switch (o) { case int x: void Assign() { x = 5; } void Print() => System.Console.WriteLine(x); break; case string x: Assign(); System.Action p = Print; p(); break; } } }"; var comp = CreateCompilationWithMscorlib46(source, parseOptions: DefaultParseOptions, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: "5"); } [Fact] [WorkItem(15536, "https://github.com/dotnet/roslyn/issues/15536")] public void CallFromDifferentSwitchSection_05() { var source = @" class Program { static void Main() { Test(string.Empty); } static void Test(object o) { switch (o) { case string x: Local1(); break; case int x: void Local1() => Local2(x = 5); break; case char x: void Local2(int y) { System.Console.WriteLine(x = 'a'); System.Console.WriteLine(y); } break; } } }"; var comp = CreateCompilationWithMscorlib46(source, parseOptions: DefaultParseOptions, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: @"a 5"); } [Fact] [WorkItem(16751, "https://github.com/dotnet/roslyn/issues/16751")] public void SemanticModelInAttribute_01() { var source = @" public class X { public static void Main() { const bool b1 = true; void Local1( [Test(p = b1)] [Test(p = b2)] int p1) { } Local1(1); } } class b1 {} class Test : System.Attribute { public bool p {get; set;} } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (10,23): error CS0103: The name 'b2' does not exist in the current context // [Test(p = b2)] Diagnostic(ErrorCode.ERR_NameNotInContext, "b2").WithArguments("b2").WithLocation(10, 23), // (6,20): warning CS0219: The variable 'b1' is assigned but its value is never used // const bool b1 = true; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "b1").WithArguments("b1").WithLocation(6, 20) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var b2 = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "b2").Single(); Assert.Null(model.GetSymbolInfo(b2).Symbol); var b1 = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "b1").Single(); var b1Symbol = model.GetSymbolInfo(b1).Symbol; Assert.Equal("System.Boolean b1", b1Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, b1Symbol.Kind); } [Fact] [WorkItem(19778, "https://github.com/dotnet/roslyn/issues/19778")] public void BindDynamicInvocation() { var source = @"using System; class C { static void M() { dynamic L<T>(Func<dynamic, T> t, object p) => p; L(m => L(d => d, null), null); L(m => L(d => d, m), null); } }"; var comp = CreateCompilationWithMscorlib45(source, references: new[] { SystemCoreRef, CSharpRef }); comp.VerifyEmitDiagnostics( // (8,18): error CS1977: Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type. // L(m => L(d => d, m), null); Diagnostic(ErrorCode.ERR_BadDynamicMethodArgLambda, "d => d").WithLocation(8, 18), // (8,16): error CS8322: Cannot pass argument with dynamic type to generic local function 'L' with inferred type arguments. // L(m => L(d => d, m), null); Diagnostic(ErrorCode.ERR_DynamicLocalFunctionTypeParameter, "L(d => d, m)").WithArguments("L").WithLocation(8, 16)); } [Fact] [WorkItem(19778, "https://github.com/dotnet/roslyn/issues/19778")] public void BindDynamicInvocation_Async() { var source = @"using System; using System.Threading.Tasks; class C { static void M() { async Task<dynamic> L<T>(Func<dynamic, T> t, object p) => await L(async m => L(async d => await d, m), p); } }"; var comp = CreateCompilationWithMscorlib45(source, references: new[] { SystemCoreRef, CSharpRef }); comp.VerifyEmitDiagnostics( // (8,37): error CS1977: Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type. // => await L(async m => L(async d => await d, m), p); Diagnostic(ErrorCode.ERR_BadDynamicMethodArgLambda, "async d => await d").WithLocation(8, 37), // (8,35): error CS8322: Cannot pass argument with dynamic type to generic local function 'L' with inferred type arguments. // => await L(async m => L(async d => await d, m), p); Diagnostic(ErrorCode.ERR_DynamicLocalFunctionTypeParameter, "L(async d => await d, m)").WithArguments("L").WithLocation(8, 35), // (8,32): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread. // => await L(async m => L(async d => await d, m), p); Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "=>").WithLocation(8, 32)); } [Fact] [WorkItem(21317, "https://github.com/dotnet/roslyn/issues/21317")] [CompilerTrait(CompilerFeature.Dynamic)] public void DynamicGenericArg() { var src = @" using System.Collections.Generic; class C { static void M() { dynamic val = 2; dynamic dynamicList = new List<int>(); void L1<T>(T x) { } L1(val); void L2<T>(int x, T y) { } L2(1, val); L2(val, 3.0f); void L3<T>(List<T> x) { } L3(dynamicList); void L4<T>(int x, params T[] y) { } L4(1, 2, val); L4(val, 3, 4); void L5<T>(T x, params int[] y) { } L5(val, 1, 2); L5(1, 3, val); } } "; VerifyDiagnostics(src, // (11,9): error CS8322: Cannot pass argument with dynamic type to generic local function 'L1'. Try specifying the type arguments explicitly. // L1(val); Diagnostic(ErrorCode.ERR_DynamicLocalFunctionTypeParameter, "L1(val)").WithArguments("L1").WithLocation(11, 9), // (14,9): error CS8322: Cannot pass argument with dynamic type to generic local function 'L2'. Try specifying the type arguments explicitly. // L2(1, val); Diagnostic(ErrorCode.ERR_DynamicLocalFunctionTypeParameter, "L2(1, val)").WithArguments("L2").WithLocation(14, 9), // (15,9): error CS8322: Cannot pass argument with dynamic type to generic local function 'L2'. Try specifying the type arguments explicitly. // L2(val, 3.0f); Diagnostic(ErrorCode.ERR_DynamicLocalFunctionTypeParameter, "L2(val, 3.0f)").WithArguments("L2").WithLocation(15, 9), // (18,9): error CS8322: Cannot pass argument with dynamic type to generic local function 'L3'. Try specifying the type arguments explicitly. // L3(dynamicList); Diagnostic(ErrorCode.ERR_DynamicLocalFunctionTypeParameter, "L3(dynamicList)").WithArguments("L3").WithLocation(18, 9), // (21,9): error CS8322: Cannot pass argument with dynamic type to generic local function 'L4'. Try specifying the type arguments explicitly. // L4(1, 2, val); Diagnostic(ErrorCode.ERR_DynamicLocalFunctionTypeParameter, "L4(1, 2, val)").WithArguments("L4").WithLocation(21, 9), // (22,9): error CS8322: Cannot pass argument with dynamic type to generic local function 'L4'. Try specifying the type arguments explicitly. // L4(val, 3, 4); Diagnostic(ErrorCode.ERR_DynamicLocalFunctionTypeParameter, "L4(val, 3, 4)").WithArguments("L4").WithLocation(22, 9), // (25,9): error CS8322: Cannot pass argument with dynamic type to generic local function 'L5'. Try specifying the type arguments explicitly. // L5(val, 1, 2); Diagnostic(ErrorCode.ERR_DynamicLocalFunctionTypeParameter, "L5(val, 1, 2)").WithArguments("L5").WithLocation(25, 9), // (26,9): error CS8322: Cannot pass argument with dynamic type to generic local function 'L5'. Try specifying the type arguments explicitly. // L5(1, 3, val); Diagnostic(ErrorCode.ERR_DynamicLocalFunctionTypeParameter, "L5(1, 3, val)").WithArguments("L5").WithLocation(26, 9) ); } [Fact] [WorkItem(23699, "https://github.com/dotnet/roslyn/issues/23699")] public void GetDeclaredSymbolOnTypeParameter() { var src = @" class C<T> { void M<U>() { void LocalFunction<T, U, V>(T p1, U p2, V p3) { } } } "; var comp = CreateCompilation(src); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var localDecl = (LocalFunctionStatementSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.LocalFunctionStatement).AsNode(); var typeParameters = localDecl.TypeParameterList.Parameters; var parameters = localDecl.ParameterList.Parameters; verifyTypeParameterAndParameter(typeParameters[0], parameters[0], "T"); verifyTypeParameterAndParameter(typeParameters[1], parameters[1], "U"); verifyTypeParameterAndParameter(typeParameters[2], parameters[2], "V"); void verifyTypeParameterAndParameter(TypeParameterSyntax typeParameter, ParameterSyntax parameter, string expected) { var symbol = model.GetDeclaredSymbol(typeParameter); Assert.Equal(expected, symbol.ToTestDisplayString()); var parameterSymbol = model.GetDeclaredSymbol(parameter); Assert.Equal(expected, parameterSymbol.Type.ToTestDisplayString()); Assert.Same(symbol, parameterSymbol.Type); } } public sealed class ScriptGlobals { public int SomeGlobal => 42; } [ConditionalFact(typeof(DesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/28001")] public void CanAccessScriptGlobalsFromInsideMethod() { var source = @" void Method() { LocalFunction(); void LocalFunction() { _ = SomeGlobal; } }"; CreateSubmission(source, new[] { ScriptTestFixtures.HostRef }, hostObjectType: typeof(ScriptGlobals)) .VerifyEmitDiagnostics(); } [ConditionalFact(typeof(DesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/28001")] public void CanAccessScriptGlobalsFromInsideLambda() { var source = @" var lambda = new System.Action(() => { LocalFunction(); void LocalFunction() { _ = SomeGlobal; } });"; CreateSubmission(source, new[] { ScriptTestFixtures.HostRef }, hostObjectType: typeof(ScriptGlobals)) .VerifyEmitDiagnostics(); } [Fact] public void CanAccessPreviousSubmissionVariablesFromInsideMethod() { var previous = CreateSubmission("int previousSubmissionVariable = 42;") .VerifyEmitDiagnostics(); var source = @" void Method() { LocalFunction(); void LocalFunction() { _ = previousSubmissionVariable; } }"; CreateSubmission(source, previous: previous) .VerifyEmitDiagnostics(); } [Fact] public void CanAccessPreviousSubmissionVariablesFromInsideLambda() { var previous = CreateSubmission("int previousSubmissionVariable = 42;") .VerifyEmitDiagnostics(); var source = @" var lambda = new System.Action(() => { LocalFunction(); void LocalFunction() { _ = previousSubmissionVariable; } });"; CreateSubmission(source, previous: previous) .VerifyEmitDiagnostics(); } [Fact] public void CanAccessPreviousSubmissionMethodsFromInsideMethod() { var previous = CreateSubmission("void PreviousSubmissionMethod() { }") .VerifyEmitDiagnostics(); var source = @" void Method() { LocalFunction(); void LocalFunction() { PreviousSubmissionMethod(); } }"; CreateSubmission(source, previous: previous) .VerifyEmitDiagnostics(); } [Fact] public void CanAccessPreviousSubmissionMethodsFromInsideLambda() { var previous = CreateSubmission("void PreviousSubmissionMethod() { }") .VerifyEmitDiagnostics(); var source = @" var lambda = new System.Action(() => { LocalFunction(); void LocalFunction() { PreviousSubmissionMethod(); } });"; CreateSubmission(source, previous: previous) .VerifyEmitDiagnostics(); } [Fact] public void ShadowNames_01() { var source = @"#pragma warning disable 0219 #pragma warning disable 8321 class Program { static void M() { void F1(object x) { string x = null; } // local void F2(object x, string y, int x) { } // parameter void F3(object x) { void x() { } } // method void F4<x, y>(object x) { void y() { } } // type parameter void F5(object M, string Program) { } } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3); verifyDiagnostics(); comp = CreateCompilation(source, parseOptions: TestOptions.Regular8); verifyDiagnostics(); comp = CreateCompilation(source); verifyDiagnostics(); void verifyDiagnostics() { comp.VerifyDiagnostics( // (7,36): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // void F1(object x) { string x = null; } // local Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(7, 36), // (8,41): error CS0100: The parameter name 'x' is a duplicate // void F2(object x, string y, int x) { } // parameter Diagnostic(ErrorCode.ERR_DuplicateParamName, "x").WithArguments("x").WithLocation(8, 41), // (9,34): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // void F3(object x) { void x() { } } // method Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(9, 34), // (10,30): error CS0412: 'x': a parameter, local variable, or local function cannot have the same name as a method type parameter // void F4<x, y>(object x) { void y() { } } // type parameter Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "x").WithArguments("x").WithLocation(10, 30), // (10,40): error CS0412: 'y': a parameter, local variable, or local function cannot have the same name as a method type parameter // void F4<x, y>(object x) { void y() { } } // type parameter Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "y").WithArguments("y").WithLocation(10, 40)); } } [Fact] public void ShadowNames_Local_01() { var source = @"#pragma warning disable 0219 #pragma warning disable 8321 using System.Linq; class Program { static void M() { object x = null; void F1() { object x = 0; } // local void F2(string x) { } // parameter void F3() { void x() { } } // method void F4<x>() { } // type parameter void F5() { _ = from x in new[] { 1, 2, 3 } select x; } // range variable } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics( // (9,28): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // void F1() { object x = 0; } // local Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(9, 28), // (10,24): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // void F2(string x) { } // parameter Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(10, 24), // (11,26): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // void F3() { void x() { } } // method Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(11, 26), // (12,17): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // void F4<x>() { } // type parameter Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(12, 17), // (13,30): error CS1931: The range variable 'x' conflicts with a previous declaration of 'x' // void F5() { _ = from x in new[] { 1, 2, 3 } select x; } // range variable Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "x").WithArguments("x").WithLocation(13, 30)); comp = CreateCompilation(source, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void ShadowNames_Local_02() { var source = @"#pragma warning disable 0219 #pragma warning disable 8321 using System.Linq; class Program { static void M() { void F1() { object x = 0; } // local void F2(string x) { } // parameter void F3() { void x() { } } // method void F4<x>() { } // type parameter void F5() { _ = from x in new[] { 1, 2, 3 } select x; } // range variable object x = null; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics( // (8,28): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // void F1() { object x = 0; } // local Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(8, 28), // (9,24): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // void F2(string x) { } // parameter Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(9, 24), // (10,26): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // void F3() { void x() { } } // method Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(10, 26), // (11,17): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // void F4<x>() { } // type parameter Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(11, 17), // (12,30): error CS1931: The range variable 'x' conflicts with a previous declaration of 'x' // void F5() { _ = from x in new[] { 1, 2, 3 } select x; } // range variable Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "x").WithArguments("x").WithLocation(12, 30)); comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void ShadowNames_Local_03() { var source = @"#pragma warning disable 0219 #pragma warning disable 8321 using System.Linq; class Program { static void M() { static void F1() { object x = 0; } // local static void F2(string x) { } // parameter static void F3() { void x() { } } // method static void F4<x>() { } // type parameter static void F5() { _ = from x in new[] { 1, 2, 3 } select x; } // range variable object x = null; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void ShadowNames_Parameter() { var source = @"#pragma warning disable 0219 #pragma warning disable 8321 using System.Linq; class Program { static void M(object x) { void F1() { object x = 0; } // local void F2(string x) { } // parameter void F3() { void x() { } } // method void F4<x>() { } // type parameter void F5() { _ = from x in new[] { 1, 2, 3 } select x; } // range variable } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3); // The conflict between the type parameter in F4<x>() and the parameter // in M(object x) is not reported, for backwards compatibility. comp.VerifyDiagnostics( // (8,28): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // void F1() { object x = 0; } // local Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(8, 28), // (9,24): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // void F2(string x) { } // parameter Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(9, 24), // (10,26): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // void F3() { void x() { } } // method Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(10, 26), // (12,30): error CS1931: The range variable 'x' conflicts with a previous declaration of 'x' // void F5() { _ = from x in new[] { 1, 2, 3 } select x; } // range variable Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "x").WithArguments("x").WithLocation(12, 30)); comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void ShadowNames_TypeParameter() { var source = @"#pragma warning disable 0219 #pragma warning disable 8321 using System.Linq; class Program { static void M<x>() { void F1() { object x = 0; } // local void F2(string x) { } // parameter void F3() { void x() { } } // method void F4<x>() { } // type parameter void F5() { _ = from x in new[] { 1, 2, 3 } select x; } // range variable } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics( // (8,28): error CS0412: 'x': a parameter, local variable, or local function cannot have the same name as a method type parameter // void F1() { object x = 0; } // local Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "x").WithArguments("x").WithLocation(8, 28), // (9,24): error CS0412: 'x': a parameter, local variable, or local function cannot have the same name as a method type parameter // void F2(string x) { } // parameter Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "x").WithArguments("x").WithLocation(9, 24), // (10,26): error CS0412: 'x': a parameter, local variable, or local function cannot have the same name as a method type parameter // void F3() { void x() { } } // method Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "x").WithArguments("x").WithLocation(10, 26), // (11,17): warning CS8387: Type parameter 'x' has the same name as the type parameter from outer method 'Program.M<x>()' // void F4<x>() { } // type parameter Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterMethodTypeParameter, "x").WithArguments("x", "Program.M<x>()").WithLocation(11, 17), // (12,30): error CS1948: The range variable 'x' cannot have the same name as a method type parameter // void F5() { _ = from x in new[] { 1, 2, 3 } select x; } // range variable Diagnostic(ErrorCode.ERR_QueryRangeVariableSameAsTypeParam, "x").WithArguments("x").WithLocation(12, 30)); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,17): warning CS8387: Type parameter 'x' has the same name as the type parameter from outer method 'Program.M<x>()' // void F4<x>() { } // type parameter Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterMethodTypeParameter, "x").WithArguments("x", "Program.M<x>()").WithLocation(11, 17)); } [Fact] public void ShadowNames_LocalFunction_01() { var source = @"#pragma warning disable 0219 #pragma warning disable 8321 using System.Linq; class Program { static void M() { void x() { } void F1() { object x = 0; } // local void F2(string x) { } // parameter void F3() { void x() { } } // method void F4<x>() { } // type parameter void F5() { _ = from x in new[] { 1, 2, 3 } select x; } // range variable } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics( // (9,28): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // void F1() { object x = 0; } // local Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(9, 28), // (10,24): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // void F2(string x) { } // parameter Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(10, 24), // (11,26): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // void F3() { void x() { } } // method Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(11, 26), // (12,17): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // void F4<x>() { } // type parameter Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(12, 17), // (13,30): error CS1931: The range variable 'x' conflicts with a previous declaration of 'x' // void F5() { _ = from x in new[] { 1, 2, 3 } select x; } // range variable Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "x").WithArguments("x").WithLocation(13, 30)); comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void ShadowNames_LocalFunction_02() { var source = @"#pragma warning disable 0219 #pragma warning disable 8321 class Program { static void M1() { void M1() { } } static void M2(object x) { void x() { } } static void M3() { object x = null; void x() { } } static void M4<T>() { void T() { } } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3); verifyDiagnostics(); comp = CreateCompilation(source); verifyDiagnostics(); void verifyDiagnostics() { comp.VerifyDiagnostics( // (11,14): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // void x() { } Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(11, 14), // (16,14): error CS0128: A local variable or function named 'x' is already defined in this scope // void x() { } Diagnostic(ErrorCode.ERR_LocalDuplicate, "x").WithArguments("x").WithLocation(16, 14), // (20,14): error CS0412: 'T': a parameter, local variable, or local function cannot have the same name as a method type parameter // void T() { } Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "T").WithArguments("T").WithLocation(20, 14)); } } [Fact] public void ShadowNames_ThisLocalFunction() { var source = @"#pragma warning disable 0219 #pragma warning disable 8321 using System.Linq; class Program { static void M() { void F1() { object F1 = 0; } // local void F2(string F2) { } // parameter void F3() { void F3() { } } // method void F4<F4>() { } // type parameter void F5() { _ = from F5 in new[] { 1, 2, 3 } select F5; } // range variable } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics( // (8,28): error CS0136: A local or parameter named 'F1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // void F1() { object F1 = 0; } // local Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "F1").WithArguments("F1").WithLocation(8, 28), // (9,24): error CS0136: A local or parameter named 'F2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // void F2(string F2) { } // parameter Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "F2").WithArguments("F2").WithLocation(9, 24), // (10,26): error CS0136: A local or parameter named 'F3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // void F3() { void F3() { } } // method Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "F3").WithArguments("F3").WithLocation(10, 26), // (11,17): error CS0136: A local or parameter named 'F4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // void F4<F4>() { } // type parameter Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "F4").WithArguments("F4").WithLocation(11, 17), // (12,30): error CS1931: The range variable 'F5' conflicts with a previous declaration of 'F5' // void F5() { _ = from F5 in new[] { 1, 2, 3 } select F5; } // range variable Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "F5").WithArguments("F5").WithLocation(12, 30)); comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void ShadowNames_LocalFunctionInsideLocalFunction_01() { var source = @"#pragma warning disable 0219 #pragma warning disable 8321 class Program { static void M<T>(object x) { void F() { void G1(int x) { } void G2() { int T = 0; } void G3<T>() { } } } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics( // (9,25): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // void G1(int x) { } Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(9, 25), // (10,29): error CS0412: 'T': a parameter, local variable, or local function cannot have the same name as a method type parameter // void G2() { int T = 0; } Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "T").WithArguments("T").WithLocation(10, 29), // (11,21): warning CS8387: Type parameter 'T' has the same name as the type parameter from outer method 'Program.M<T>(object)' // void G3<T>() { } Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterMethodTypeParameter, "T").WithArguments("T", "Program.M<T>(object)").WithLocation(11, 21)); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,21): warning CS8387: Type parameter 'T' has the same name as the type parameter from outer method 'Program.M<T>(object)' // void G3<T>() { } Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterMethodTypeParameter, "T").WithArguments("T", "Program.M<T>(object)").WithLocation(11, 21)); } [Fact] public void ShadowNames_LocalFunctionInsideLocalFunction_02() { var source = @"#pragma warning disable 0219 #pragma warning disable 8321 class Program { static void M<T>(object x) { static void F1() { void G1(int x) { } } void F2() { static void G2() { int T = 0; } } static void F3() { static void G3<T>() { } } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (17,28): warning CS8387: Type parameter 'T' has the same name as the type parameter from outer method 'Program.M<T>(object)' // static void G3<T>() { } Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterMethodTypeParameter, "T").WithArguments("T", "Program.M<T>(object)").WithLocation(17, 28)); } [Fact] public void ShadowNames_LocalFunctionInsideLambda_01() { var source = @"#pragma warning disable 0219 #pragma warning disable 8321 using System; class Program { static void M() { Action a1 = () => { int x = 0; void F1() { object x = null; } }; Action a2 = () => { int T = 0; void F2<T>() { } }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics( // (11,32): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // void F1() { object x = null; } Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(11, 32), // (16,21): error CS0136: A local or parameter named 'T' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // void F2<T>() { } Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "T").WithArguments("T").WithLocation(16, 21)); comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void ShadowNames_LocalFunctionInsideLambda_02() { var source = @"#pragma warning disable 0219 #pragma warning disable 8321 using System; class Program { static void M() { Action<int> a1 = x => { void F1(object x) { } }; Action<int> a2 = (int T) => { void F2<T>() { } }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3); // The conflict between the type parameter in F2<T>() and the parameter // in a2 is not reported, for backwards compatibility. comp.VerifyDiagnostics( // (10,28): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // void F1(object x) { } Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(10, 28)); comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void ShadowNames_LocalFunctionInsideLambda_03() { var source = @"using System; class Program { static void M() { Action<int> a = x => { void x() { } x(); }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3); // The conflict between the local function and the parameter is not reported, // for backwards compatibility. comp.VerifyDiagnostics(); comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void StaticWithThisReference() { var source = @"#pragma warning disable 8321 class C { void M() { static object F1() => this.GetHashCode(); static object F2() => base.GetHashCode(); static void F3() { object G3() => ToString(); } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,31): error CS8422: A static local function cannot contain a reference to 'this' or 'base'. // static object F1() => this.GetHashCode(); Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureThis, "this").WithLocation(6, 31), // (7,31): error CS8422: A static local function cannot contain a reference to 'this' or 'base'. // static object F2() => base.GetHashCode(); Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureThis, "base").WithLocation(7, 31), // (10,28): error CS8422: A static local function cannot contain a reference to 'this' or 'base'. // object G3() => ToString(); Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureThis, "ToString").WithLocation(10, 28)); } [Fact] public void StaticWithVariableReference() { var source = @"#pragma warning disable 8321 class C { static void M(object x) { object y = null; static object F1() => x; static object F2() => y; static void F3() { object G3() => x; } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,31): error CS8421: A static local function cannot contain a reference to 'x'. // static object F1() => x; Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "x").WithArguments("x").WithLocation(7, 31), // (8,31): error CS8421: A static local function cannot contain a reference to 'y'. // static object F2() => y; Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "y").WithArguments("y").WithLocation(8, 31), // (11,28): error CS8421: A static local function cannot contain a reference to 'x'. // object G3() => x; Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "x").WithArguments("x").WithLocation(11, 28)); } [Fact] public void StaticWithLocalFunctionVariableReference_01() { var source = @"#pragma warning disable 8321 class C { static void M() { static void F(object x) { object y = null; object G1() => x ?? y; static object G2() => x ?? y; } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,35): error CS8421: A static local function cannot contain a reference to 'x'. // static object G2() => x ?? y; Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "x").WithArguments("x").WithLocation(10, 35), // (10,40): error CS8421: A static local function cannot contain a reference to 'y'. // static object G2() => x ?? y; Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "y").WithArguments("y").WithLocation(10, 40)); } [Fact] public void StaticWithLocalFunctionVariableReference_02() { var source = @"#pragma warning disable 8321 class C { static void M(int x) { static void F1(int y) { int F2() => x + y; } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,25): error CS8421: A static local function cannot contain a reference to 'x'. // int F2() => x + y; Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "x").WithArguments("x").WithLocation(8, 25)); } /// <summary> /// Can reference type parameters from enclosing scope. /// </summary> [Fact] public void StaticWithTypeParameterReferences() { var source = @"using static System.Console; class A<T> { internal string F1() { static string L1() => typeof(T).FullName; return L1(); } } class B { internal string F2<T>() { static string L2() => typeof(T).FullName; return L2(); } internal static string F3() { static string L3<T>() { static string L4() => typeof(T).FullName; return L4(); } return L3<byte>(); } } class Program { static void Main() { WriteLine(new A<int>().F1()); WriteLine(new B().F2<string>()); WriteLine(B.F3()); } }"; CompileAndVerify(source, expectedOutput: @"System.Int32 System.String System.Byte"); } [Fact] public void Conditional_ThisReferenceInStatic() { var source = @"#pragma warning disable 0649 #pragma warning disable 8321 using System.Diagnostics; class A { internal object _f; } class B : A { [Conditional(""MyDefine"")] static void F(object o) { } void M() { static void F1() { F(this); } static void F2() { F(base._f); } static void F3() { F(_f); } } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular.WithPreprocessorSymbols("MyDefine")); verifyDiagnostics(); comp = CreateCompilation(source, parseOptions: TestOptions.Regular); verifyDiagnostics(); void verifyDiagnostics() { comp.VerifyDiagnostics( // (16,30): error CS8422: A static local function cannot contain a reference to 'this' or 'base'. // static void F1() { F(this); } Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureThis, "this").WithLocation(16, 30), // (17,30): error CS8422: A static local function cannot contain a reference to 'this' or 'base'. // static void F2() { F(base._f); } Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureThis, "base").WithLocation(17, 30), // (18,30): error CS8422: A static local function cannot contain a reference to 'this' or 'base'. // static void F3() { F(_f); } Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureThis, "_f").WithLocation(18, 30)); } } [Fact] public void LocalFunctionConditional_Errors() { var source = @" using System.Diagnostics; class C { void M() { #pragma warning disable 8321 // Unreferenced local function [Conditional(""DEBUG"")] // 1 int local1() => 42; [Conditional(""DEBUG"")] // 2 void local2(out int i) { i = 42; } } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (10,10): error CS0578: The Conditional attribute is not valid on 'local1()' because its return type is not void // [Conditional("DEBUG")] // 1 Diagnostic(ErrorCode.ERR_ConditionalMustReturnVoid, @"Conditional(""DEBUG"")").WithArguments("local1()").WithLocation(10, 10), // (13,10): error CS0685: Conditional member 'local2(out int)' cannot have an out parameter // [Conditional("DEBUG")] // 2 Diagnostic(ErrorCode.ERR_ConditionalWithOutParam, @"Conditional(""DEBUG"")").WithArguments("local2(out int)").WithLocation(13, 10)); } [Fact] public void LocalFunctionObsolete() { var source = @" using System; class C { void M1() { local1(); // 1 local2(); // 2 [Obsolete] void local1() { } [Obsolete(""hello"", true)] void local2() { } #pragma warning disable 8321 // Unreferenced local function [Obsolete] void local3() { // no diagnostics expected when calling an Obsolete method within an Obsolete method local1(); local2(); } } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,9): warning CS0612: 'local1()' is obsolete // local1(); // 1 Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "local1()").WithArguments("local1()").WithLocation(8, 9), // (9,9): error CS0619: 'local2()' is obsolete: 'hello' // local2(); // 2 Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "local2()").WithArguments("local2()", "hello").WithLocation(9, 9)); } [Fact] public void LocalFunction_AttributeMarkedObsolete() { var source = @" using System; [Obsolete] class Attr : Attribute { } class C { void M1() { #pragma warning disable 8321 [Attr] void local1() { } // 1 [return: Attr] void local2() { } // 2 void local3([Attr] int i) { } // 3 void local4<[Attr] T>(T t) { } // 4 } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (12,10): warning CS0612: 'Attr' is obsolete // [Attr] void local1() { } // 1 Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "Attr").WithArguments("Attr").WithLocation(12, 10), // (13,18): warning CS0612: 'Attr' is obsolete // [return: Attr] void local2() { } // 2 Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "Attr").WithArguments("Attr").WithLocation(13, 18), // (14,22): warning CS0612: 'Attr' is obsolete // void local3([Attr] int i) { } // 3 Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "Attr").WithArguments("Attr").WithLocation(14, 22), // (15,22): warning CS0612: 'Attr' is obsolete // void local4<[Attr] T>(T t) { } // 4 Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "Attr").WithArguments("Attr").WithLocation(15, 22)); } [Fact] public void LocalFunction_NotNullIfNotNullAttribute() { var source = @" using System.Diagnostics.CodeAnalysis; #nullable enable class C { void M() { _ = local1(null).ToString(); // 1 _ = local1(""hello"").ToString(); [return: NotNullIfNotNull(""s1"")] string? local1(string? s1) => s1; } } "; var comp = CreateCompilation(new[] { NotNullIfNotNullAttributeDefinition, source }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (10,13): warning CS8602: Dereference of a possibly null reference. // _ = local1(null).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "local1(null)").WithLocation(10, 13)); } [Fact] public void LocalFunction_MaybeNullWhenAttribute() { var source = @" #nullable enable using System.Diagnostics.CodeAnalysis; class C { void M() { _ = tryGetValue(true, out var s) ? s.ToString() : s.ToString(); // 1 bool tryGetValue(bool b, [MaybeNullWhen(false)] out string s1) { s1 = b ? ""abc"" : null; return b; } } } "; var comp = CreateCompilation(new[] { MaybeNullWhenAttributeDefinition, source }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (12,15): warning CS8602: Dereference of a possibly null reference. // : s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(12, 15)); } [Fact] public void LocalFunction_MaybeNullWhenAttribute_CheckUsage() { var source = @" #nullable enable using System.Diagnostics.CodeAnalysis; class C { void M() { var s = ""abc""; local1(); tryGetValue(""a"", out s); local1(); void local1() { _ = s.ToString(); // 1 } bool tryGetValue(string key, [MaybeNullWhen(false)] out string s1) { s1 = key; return true; } } } "; var comp = CreateCompilation(new[] { MaybeNullWhenAttributeDefinition, source }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (18,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(18, 17)); } [Fact] public void LocalFunction_AllowNullAttribute() { var source = @" #nullable enable using System.Diagnostics.CodeAnalysis; class C { void M<T>([AllowNull] T t1, T t2) { local1(t1); local1(t2); local2(t1); // 1 local2(t2); void local1([AllowNull] T t) { } void local2(T t) { } } } "; var comp = CreateCompilation(new[] { AllowNullAttributeDefinition, source }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (13,16): warning CS8604: Possible null reference argument for parameter 't' in 'void local2(T t)'. // local2(t1); // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t1").WithArguments("t", "void local2(T t)").WithLocation(13, 16)); } [Fact] public void LocalFunction_MaybeNullAttribute() { var source = @" #nullable enable using System.Diagnostics.CodeAnalysis; class C { void M<TOuter>() { getDefault<string>().ToString(); // 1 getDefault<string?>().ToString(); // 2 getDefault<int>().ToString(); getDefault<int?>().Value.ToString(); // 3 getDefault<TOuter>().ToString(); // 4 [return: MaybeNull] T getDefault<T>() => default(T); } } "; var comp = CreateCompilation(new[] { MaybeNullAttributeDefinition, source }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // getDefault<string>().ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "getDefault<string>()").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // getDefault<string?>().ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "getDefault<string?>()").WithLocation(11, 9), // (13,9): warning CS8629: Nullable value type may be null. // getDefault<int?>().Value.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "getDefault<int?>()").WithLocation(13, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // getDefault<TOuter>().ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "getDefault<TOuter>()").WithLocation(14, 9)); } [Fact] public void LocalFunction_Nullable_CheckUsage_DoesNotUsePostconditions() { var source = @" #nullable enable using System.Diagnostics.CodeAnalysis; class C { void M() { var s0 = ""hello""; local1(out s0); bool local1([MaybeNullWhen(false)] out string s1) { s0.ToString(); s1 = ""world""; return true; } } } "; var comp = CreateCompilation(new[] { MaybeNullWhenAttributeDefinition, source }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); } [Fact] public void LocalFunction_DoesNotReturn() { var source = @" #nullable enable using System.Diagnostics.CodeAnalysis; class C { void M(string? s) { local1(); s.ToString(); [DoesNotReturn] void local1() { throw null!; } } } "; var comp = CreateCompilation(new[] { DoesNotReturnAttributeDefinition, source }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); } [Fact] public void LocalFunction_DoesNotReturnIf() { var source = @" #nullable enable using System.Diagnostics.CodeAnalysis; class C { void M(string? s1, string? s2) { local1(s1 != null); s1.ToString(); local1(false); s2.ToString(); void local1([DoesNotReturnIf(false)] bool b) { throw null!; } } } "; var comp = CreateCompilation(new[] { DoesNotReturnIfAttributeDefinition, source }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); } [Fact] public void NameOf_ThisReferenceInStatic() { var source = @"#pragma warning disable 8321 class C { void M() { static object F1() => nameof(this.ToString); static object F2() => nameof(base.GetHashCode); static object F3() => nameof(M); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void NameOf_InstanceMemberInStatic() { var source = @"#pragma warning disable 0649 #pragma warning disable 8321 class C { object _f; static void M() { _ = nameof(_f); static object F() => nameof(_f); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = GetNameOfExpressions(tree)[1]; var symbol = model.GetSymbolInfo(expr).Symbol; Assert.Equal("System.Object C._f", symbol.ToTestDisplayString()); } [Fact] public void NameOf_CapturedVariableInStatic() { var source = @"#pragma warning disable 8321 class C { static void M(object x) { static object F() => nameof(x); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = GetNameOfExpressions(tree)[0]; var symbol = model.GetSymbolInfo(expr).Symbol; Assert.Equal("System.Object x", symbol.ToTestDisplayString()); } /// <summary> /// nameof(x) should bind to shadowing symbol. /// </summary> [Fact] public void NameOf_ShadowedVariable() { var source = @"#pragma warning disable 8321 class C { static void M(object x) { object F() { int x = 0; return nameof(x); } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = GetNameOfExpressions(tree)[0]; var symbol = model.GetSymbolInfo(expr).Symbol; Assert.Equal(SymbolKind.Local, symbol.Kind); Assert.Equal("System.Int32 x", symbol.ToTestDisplayString()); } /// <summary> /// nameof(T) should bind to shadowing symbol. /// </summary> [Fact] public void NameOf_ShadowedTypeParameter() { var source = @"#pragma warning disable 8321 class C { static void M<T>() { object F1() { int T = 0; return nameof(T); } object F2<T>() { return nameof(T); } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,19): warning CS8387: Type parameter 'T' has the same name as the type parameter from outer method 'C.M<T>()' // object F2<T>() Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterMethodTypeParameter, "T").WithArguments("T", "C.M<T>()").WithLocation(11, 19)); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var exprs = GetNameOfExpressions(tree); var symbol = model.GetSymbolInfo(exprs[0]).Symbol; Assert.Equal(SymbolKind.Local, symbol.Kind); Assert.Equal("System.Int32 T", symbol.ToTestDisplayString()); symbol = model.GetSymbolInfo(exprs[1]).Symbol; Assert.Equal(SymbolKind.TypeParameter, symbol.Kind); Assert.Equal("System.Object F2<T>()", symbol.ContainingSymbol.ToTestDisplayString()); } /// <summary> /// typeof(T) should bind to nearest type. /// </summary> [Fact] public void TypeOf_ShadowedTypeParameter() { var source = @"#pragma warning disable 0219 #pragma warning disable 8321 class C { static void M<T>() { object F1() { int T = 0; return typeof(T); } object F2<T>() { return typeof(T); } object F3<U>() { return typeof(U); } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (12,19): warning CS8387: Type parameter 'T' has the same name as the type parameter from outer method 'C.M<T>()' // object F2<T>() Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterMethodTypeParameter, "T").WithArguments("T", "C.M<T>()").WithLocation(12, 19)); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var exprs = tree.GetRoot().DescendantNodes().OfType<TypeOfExpressionSyntax>().Select(n => n.Type).ToImmutableArray(); var symbol = model.GetSymbolInfo(exprs[0]).Symbol; Assert.Equal(SymbolKind.TypeParameter, symbol.Kind); Assert.Equal("void C.M<T>()", symbol.ContainingSymbol.ToTestDisplayString()); symbol = model.GetSymbolInfo(exprs[1]).Symbol; Assert.Equal(SymbolKind.TypeParameter, symbol.Kind); Assert.Equal("System.Object F2<T>()", symbol.ContainingSymbol.ToTestDisplayString()); symbol = model.GetSymbolInfo(exprs[2]).Symbol; Assert.Equal(SymbolKind.TypeParameter, symbol.Kind); Assert.Equal("System.Object F3<U>()", symbol.ContainingSymbol.ToTestDisplayString()); } /// <summary> /// sizeof(T) should bind to nearest type. /// </summary> [Fact] public void SizeOf_ShadowedTypeParameter() { var source = @"#pragma warning disable 0219 #pragma warning disable 8321 unsafe class C { static void M<T>() where T : unmanaged { object F1() { int T = 0; return sizeof(T); } object F2<T>() where T : unmanaged { return sizeof(T); } object F3<U>() where U : unmanaged { return sizeof(U); } } }"; var comp = CreateCompilation(source, options: TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (12,19): warning CS8387: Type parameter 'T' has the same name as the type parameter from outer method 'C.M<T>()' // object F2<T>() Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterMethodTypeParameter, "T").WithArguments("T", "C.M<T>()").WithLocation(12, 19)); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var exprs = tree.GetRoot().DescendantNodes().OfType<SizeOfExpressionSyntax>().Select(n => n.Type).ToImmutableArray(); var symbol = model.GetSymbolInfo(exprs[0]).Symbol; Assert.Equal(SymbolKind.TypeParameter, symbol.Kind); Assert.Equal("void C.M<T>()", symbol.ContainingSymbol.ToTestDisplayString()); symbol = model.GetSymbolInfo(exprs[1]).Symbol; Assert.Equal(SymbolKind.TypeParameter, symbol.Kind); Assert.Equal("System.Object F2<T>()", symbol.ContainingSymbol.ToTestDisplayString()); symbol = model.GetSymbolInfo(exprs[2]).Symbol; Assert.Equal(SymbolKind.TypeParameter, symbol.Kind); Assert.Equal("System.Object F3<U>()", symbol.ContainingSymbol.ToTestDisplayString()); } private static ImmutableArray<ExpressionSyntax> GetNameOfExpressions(SyntaxTree tree) { return tree.GetRoot().DescendantNodes(). OfType<InvocationExpressionSyntax>(). Where(n => n.Expression.ToString() == "nameof"). Select(n => n.ArgumentList.Arguments[0].Expression). ToImmutableArray(); } [Fact] public void ShadowWithSelfReferencingLocal() { var source = @"using System; class Program { static void Main() { int x = 13; void Local() { int x = (x = 0) + 42; Console.WriteLine(x); } Local(); Console.WriteLine(x); } }"; CompileAndVerify(source, expectedOutput: @"42 13"); } [Fact, WorkItem(38129, "https://github.com/dotnet/roslyn/issues/38129")] public void StaticLocalFunctionLocalFunctionReference_01() { var source = @"#pragma warning disable 8321 class C { static void M() { void F1() {} static void F2() {} static void F3() { F1(); F2(); } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,13): error CS8421: A static local function cannot contain a reference to 'F1'. // F1(); Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "F1()").WithArguments("F1").WithLocation(11, 13)); } [Fact, WorkItem(39706, "https://github.com/dotnet/roslyn/issues/39706")] public void StaticLocalFunctionLocalFunctionReference_02() { var source = @"#pragma warning disable 8321 class Program { static void Method() { void Local<T>() {} static void StaticLocal() { Local<int>(); } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,13): error CS8421: A static local function cannot contain a reference to 'Local'. // Local<int>(); Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "Local<int>()").WithArguments("Local").WithLocation(9, 13)); } [Fact, WorkItem(39706, "https://github.com/dotnet/roslyn/issues/39706")] public void StaticLocalFunctionLocalFunctionReference_03() { var source = @"using System; class Program { static void Method() { int i = 0; void Local<T>() { i = 0; } Action a = () => i++; static void StaticLocal() { Local<int>(); } StaticLocal(); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (14,13): error CS8421: A static local function cannot contain a reference to 'Local'. // Local<int>(); Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "Local<int>()").WithArguments("Local").WithLocation(14, 13)); } [Fact, WorkItem(38240, "https://github.com/dotnet/roslyn/issues/38240")] public void StaticLocalFunctionLocalFunctionDelegateReference_01() { var source = @"#pragma warning disable 8321 using System; class C { static void M() { void F1() {} static void F2() { Action a = F1; _ = new Action(F1); } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,24): error CS8421: A static local function cannot contain a reference to 'F1'. // Action a = F1; Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "F1").WithArguments("F1").WithLocation(11, 24), // (12,28): error CS8421: A static local function cannot contain a reference to 'F1'. // _ = new Action(F1); Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "F1").WithArguments("F1").WithLocation(12, 28)); } [Fact, WorkItem(39706, "https://github.com/dotnet/roslyn/issues/39706")] public void StaticLocalFunctionLocalFunctionDelegateReference_02() { var source = @"#pragma warning disable 8321 using System; class Program { static void Method() { void Local<T>() {} static void StaticLocal() { Action a; a = Local<int>; a = new Action(Local<string>); } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,17): error CS8421: A static local function cannot contain a reference to 'Local'. // a = Local<int>; Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "Local<int>").WithArguments("Local").WithLocation(11, 17), // (12,28): error CS8421: A static local function cannot contain a reference to 'Local'. // a = new Action(Local<string>); Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "Local<string>").WithArguments("Local").WithLocation(12, 28)); } [Fact, WorkItem(39706, "https://github.com/dotnet/roslyn/issues/39706")] public void StaticLocalFunctionLocalFunctionDelegateReference_03() { var source = @"using System; class Program { static void Method() { int i = 0; void Local<T>() { i = 0; } Action a = () => i++; a = StaticLocal(); static Action StaticLocal() { return Local<int>; } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (15,20): error CS8421: A static local function cannot contain a reference to 'Local'. // return Local<int>; Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "Local<int>").WithArguments("Local").WithLocation(15, 20)); } [Fact] public void StaticLocalFunctionGenericStaticLocalFunction() { var source = @"using System; class Program { static void Main() { static void F1<T>() { Console.WriteLine(typeof(T)); } static void F2() { F1<int>(); Action a = F1<string>; a(); } F2(); } }"; CompileAndVerify(source, expectedOutput: @"System.Int32 System.String"); } [Fact, WorkItem(38240, "https://github.com/dotnet/roslyn/issues/38240")] public void StaticLocalFunctionStaticFunctionsDelegateReference() { var source = @"#pragma warning disable 8321 using System; class C { static void M() { static void F1() {} static void F2() { Action m = M; Action f1 = F1; _ = new Action(M); _ = new Action(F1); } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact, WorkItem(38240, "https://github.com/dotnet/roslyn/issues/38240")] public void StaticLocalFunctionThisAndBaseDelegateReference() { var source = @"#pragma warning disable 8321 using System; class B { public virtual void M() {} } class C : B { public override void M() { static void F() { Action a1 = base.M; Action a2 = this.M; Action a3 = M; _ = new Action(base.M); _ = new Action(this.M); _ = new Action(M); } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (14,25): error CS8422: A static local function cannot contain a reference to 'this' or 'base'. // Action a1 = base.M; Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureThis, "base").WithLocation(14, 25), // (15,25): error CS8422: A static local function cannot contain a reference to 'this' or 'base'. // Action a2 = this.M; Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureThis, "this").WithLocation(15, 25), // (16,25): error CS8422: A static local function cannot contain a reference to 'this' or 'base'. // Action a3 = M; Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureThis, "M").WithLocation(16, 25), // (17,28): error CS8422: A static local function cannot contain a reference to 'this' or 'base'. // _ = new Action(base.M); Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureThis, "base").WithLocation(17, 28), // (18,28): error CS8422: A static local function cannot contain a reference to 'this' or 'base'. // _ = new Action(this.M); Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureThis, "this").WithLocation(18, 28), // (19,28): error CS8422: A static local function cannot contain a reference to 'this' or 'base'. // _ = new Action(M); Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureThis, "M").WithLocation(19, 28)); } [Fact, WorkItem(38240, "https://github.com/dotnet/roslyn/issues/38240")] public void StaticLocalFunctionDelegateReferenceWithReceiver() { var source = @"#pragma warning disable 649 #pragma warning disable 8321 using System; class C { object f; void M() { object l; static void F1() { _ = new Func<int>(f.GetHashCode); _ = new Func<int>(l.GetHashCode); } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (14,31): error CS8422: A static local function cannot contain a reference to 'this' or 'base'. // _ = new Func<int>(f.GetHashCode); Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureThis, "f").WithLocation(14, 31), // (15,31): error CS8421: A static local function cannot contain a reference to 'l'. // _ = new Func<int>(l.GetHashCode); Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "l").WithArguments("l").WithLocation(15, 31)); } [Fact] [WorkItem(38143, "https://github.com/dotnet/roslyn/issues/38143")] public void EmittedAsStatic_01() { var source = @"class Program { static void M() { static void local() { } System.Action action = local; } }"; CompileAndVerify(source, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: m => { var method = (MethodSymbol)m.GlobalNamespace.GetMember("Program.<M>g__local|0_0"); Assert.True(method.IsStatic); }); } [Fact] [WorkItem(38143, "https://github.com/dotnet/roslyn/issues/38143")] public void EmittedAsStatic_02() { var source = @"class Program { static void M<T>() { static void local(T t) { System.Console.Write(t.GetType().FullName); } System.Action<T> action = local; action(default(T)); } static void Main() { M<int>(); } }"; CompileAndVerify(source, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), expectedOutput: "System.Int32", symbolValidator: m => { var method = (MethodSymbol)m.GlobalNamespace.GetMember("Program.<M>g__local|0_0"); Assert.True(method.IsStatic); Assert.True(method.IsGenericMethod); Assert.Equal("void Program.<M>g__local|0_0<T>(T t)", method.ToTestDisplayString()); }); } /// <summary> /// Local function in generic method is emitted as a generic /// method even if no references to type parameters. /// </summary> [Fact] [WorkItem(38143, "https://github.com/dotnet/roslyn/issues/38143")] public void EmittedAsStatic_03() { var source = @"class Program { static void M<T>() where T : new() { static void local(object o) { System.Console.Write(o.GetType().FullName); } local(new T()); } static void Main() { M<int>(); } }"; CompileAndVerify(source, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), expectedOutput: "System.Int32", symbolValidator: m => { var method = (MethodSymbol)m.GlobalNamespace.GetMember("Program.<M>g__local|0_0"); Assert.True(method.IsStatic); Assert.True(method.IsGenericMethod); Assert.Equal("void Program.<M>g__local|0_0<T>(System.Object o)", method.ToTestDisplayString()); }); } /// <summary> /// Emit 'call' rather than 'callvirt' for local functions regardless of whether /// the local function is static. /// </summary> [Fact] public void EmitCallInstruction() { var source = @"using static System.Console; class Program { static void Main() { int i; void L1() => WriteLine(i++); static void L2(int i) => WriteLine(i); i = 1; L1(); L2(i); } }"; var verifier = CompileAndVerify(source, expectedOutput: @"1 2"); verifier.VerifyIL("Program.Main", @"{ // Code size 27 (0x1b) .maxstack 2 .locals init (Program.<>c__DisplayClass0_0 V_0) //CS$<>8__locals0 IL_0000: ldloca.s V_0 IL_0002: ldc.i4.1 IL_0003: stfld ""int Program.<>c__DisplayClass0_0.i"" IL_0008: ldloca.s V_0 IL_000a: call ""void Program.<Main>g__L1|0_0(ref Program.<>c__DisplayClass0_0)"" IL_000f: ldloc.0 IL_0010: ldfld ""int Program.<>c__DisplayClass0_0.i"" IL_0015: call ""void Program.<Main>g__L2|0_1(int)"" IL_001a: ret }"); } /// <summary> /// '_' should bind to '_' symbol in outer scope even in static local function. /// </summary> [Fact] public void UnderscoreInOuterScope() { var source = @"#pragma warning disable 8321 class C1 { object _; void F1() { void A1(object x) => _ = x; static void B1(object y) => _ = y; } } class C2 { static void F2() { object _; void A2(object x) => _ = x; static void B2(object y) => _ = y; } static void F3() { void A3(object x) => _ = x; static void B3(object y) => _ = y; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,37): error CS8422: A static local function cannot contain a reference to 'this' or 'base'. // static void B1(object y) => _ = y; Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureThis, "_").WithLocation(8, 37), // (17,37): error CS8421: A static local function cannot contain a reference to '_'. // static void B2(object y) => _ = y; Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "_").WithArguments("_").WithLocation(17, 37)); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var nodes = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>(); var actualSymbols = nodes.Select(n => model.GetSymbolInfo(n.Left).Symbol).Select(s => $"{s.Kind}: {s.ToTestDisplayString()}").ToArray(); var expectedSymbols = new[] { "Field: System.Object C1._", "Field: System.Object C1._", "Local: System.Object _", "Local: System.Object _", "Discard: System.Object _", "Discard: System.Object _", }; AssertEx.Equal(expectedSymbols, actualSymbols); } /// <summary> /// 'var' should bind to 'var' symbol in outer scope even in static local function. /// </summary> [Fact] public void VarInOuterScope() { var source = @"#pragma warning disable 8321 class C1 { class var { } static void F1() { void A1(object x) { var y = x; } static void B1(object x) { var y = x; } } } namespace N { using var = System.String; class C2 { static void F2() { void A2(object x) { var y = x; } static void B3(object x) { var y = x; } } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,37): error CS0266: Cannot implicitly convert type 'object' to 'C1.var'. An explicit conversion exists (are you missing a cast?) // void A1(object x) { var y = x; } Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x").WithArguments("object", "C1.var").WithLocation(7, 37), // (8,44): error CS0266: Cannot implicitly convert type 'object' to 'C1.var'. An explicit conversion exists (are you missing a cast?) // static void B1(object x) { var y = x; } Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x").WithArguments("object", "C1.var").WithLocation(8, 44), // (18,41): error CS0266: Cannot implicitly convert type 'object' to 'string'. An explicit conversion exists (are you missing a cast?) // void A2(object x) { var y = x; } Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x").WithArguments("object", "string").WithLocation(18, 41), // (19,48): error CS0266: Cannot implicitly convert type 'object' to 'string'. An explicit conversion exists (are you missing a cast?) // static void B3(object x) { var y = x; } Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x").WithArguments("object", "string").WithLocation(19, 48)); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var nodes = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>(); var actualSymbols = nodes.Select(n => model.GetDeclaredSymbol(n)).ToTestDisplayStrings(); var expectedSymbols = new[] { "C1.var y", "C1.var y", "System.String y", "System.String y", }; AssertEx.Equal(expectedSymbols, actualSymbols); } [Fact] public void AwaitWithinAsyncOuterScope_01() { var source = @"#pragma warning disable 1998 #pragma warning disable 8321 using System.Threading.Tasks; class Program { void F1() { void A1() { await Task.Yield(); } static void B1() { await Task.Yield(); } } void F2() { async void A2() { await Task.Yield(); } async static void B2() { await Task.Yield(); } } async void F3() { void A3() { await Task.Yield(); } static void B3() { await Task.Yield(); } } async void F4() { async void A4() { await Task.Yield(); } async static void B4() { await Task.Yield(); } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,21): error CS4033: The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'. // void A1() { await Task.Yield(); } Diagnostic(ErrorCode.ERR_BadAwaitWithoutVoidAsyncMethod, "await Task.Yield()").WithLocation(8, 21), // (9,28): error CS4033: The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'. // static void B1() { await Task.Yield(); } Diagnostic(ErrorCode.ERR_BadAwaitWithoutVoidAsyncMethod, "await Task.Yield()").WithLocation(9, 28), // (18,21): error CS4033: The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'. // void A3() { await Task.Yield(); } Diagnostic(ErrorCode.ERR_BadAwaitWithoutVoidAsyncMethod, "await Task.Yield()").WithLocation(18, 21), // (19,28): error CS4033: The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'. // static void B3() { await Task.Yield(); } Diagnostic(ErrorCode.ERR_BadAwaitWithoutVoidAsyncMethod, "await Task.Yield()").WithLocation(19, 28)); } /// <summary> /// 'await' should be a contextual keyword in the same way, /// regardless of whether local function is static. /// </summary> [Fact] public void AwaitWithinAsyncOuterScope_02() { var source = @"#pragma warning disable 1998 #pragma warning disable 8321 class Program { void F1() { void A1<await>() { } static void B1<await>() { } } void F2() { async void A2<await>() { } async static void B2<await>() { } } async void F3() { void A3<await>() { } static void B3<await>() { } } async void F4() { async void A4<await>() { } async static void B4<await>() { } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (12,23): error CS4003: 'await' cannot be used as an identifier within an async method or lambda expression // async void A2<await>() { } Diagnostic(ErrorCode.ERR_BadAwaitAsIdentifier, "await").WithLocation(12, 23), // (13,30): error CS4003: 'await' cannot be used as an identifier within an async method or lambda expression // async static void B2<await>() { } Diagnostic(ErrorCode.ERR_BadAwaitAsIdentifier, "await").WithLocation(13, 30), // (22,23): error CS4003: 'await' cannot be used as an identifier within an async method or lambda expression // async void A4<await>() { } Diagnostic(ErrorCode.ERR_BadAwaitAsIdentifier, "await").WithLocation(22, 23), // (23,30): error CS4003: 'await' cannot be used as an identifier within an async method or lambda expression // async static void B4<await>() { } Diagnostic(ErrorCode.ERR_BadAwaitAsIdentifier, "await").WithLocation(23, 30)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using System; using System.Collections.Immutable; using System.Linq; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class LocalFunctionsTestBase : CSharpTestBase { internal static readonly CSharpParseOptions DefaultParseOptions = TestOptions.Regular; internal static void VerifyDiagnostics(string source, params DiagnosticDescription[] expected) { var comp = CreateCompilationWithMscorlib45AndCSharp(source, options: TestOptions.ReleaseDll, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics(expected); } } [CompilerTrait(CompilerFeature.LocalFunctions)] public class LocalFunctionTests : LocalFunctionsTestBase { [Fact, WorkItem(29656, "https://github.com/dotnet/roslyn/issues/29656")] public void RefReturningAsyncLocalFunction() { var source = @" public class C { async ref System.Threading.Tasks.Task M() { } public void M2() { _ = local(); async ref System.Threading.Tasks.Task local() { } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,11): error CS1073: Unexpected token 'ref' // async ref System.Threading.Tasks.Task M() { } Diagnostic(ErrorCode.ERR_UnexpectedToken, "ref").WithArguments("ref").WithLocation(4, 11), // (4,43): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread. // async ref System.Threading.Tasks.Task M() { } Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "M").WithLocation(4, 43), // (10,15): error CS1073: Unexpected token 'ref' // async ref System.Threading.Tasks.Task local() { } Diagnostic(ErrorCode.ERR_UnexpectedToken, "ref").WithArguments("ref").WithLocation(10, 15), // (10,47): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread. // async ref System.Threading.Tasks.Task local() { } Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "local").WithLocation(10, 47) ); } [ConditionalFact(typeof(DesktopOnly))] public void LocalFunctionResetsLockScopeFlag() { var source = @" using System; using System.Threading.Tasks; class C { static void Main() { lock (new Object()) { async Task localFunc() { Console.Write(""localFunc""); await Task.Yield(); } localFunc(); } } } "; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "localFunc"); } [ConditionalFact(typeof(DesktopOnly))] public void LocalFunctionResetsTryCatchFinallyScopeFlags() { var source = @" using System; using System.Collections.Generic; class C { static void Main() { try { IEnumerable<int> localFunc() { yield return 1; } foreach (int i in localFunc()) { Console.Write(i); } throw new Exception(); } catch (Exception) { IEnumerable<int> localFunc() { yield return 2; } foreach (int i in localFunc()) { Console.Write(i); } } finally { IEnumerable<int> localFunc() { yield return 3; } foreach (int i in localFunc()) { Console.Write(i); } } } } "; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "123"); } [ConditionalFact(typeof(DesktopOnly))] public void LocalFunctionDoesNotOverwriteInnerLockScopeFlag() { var source = @" using System; using System.Collections.Generic; using System.Threading.Tasks; class C { void M(List<Task> listOfTasks) { lock (new Object()) { async Task localFunc() { lock (new Object()) { await Task.Yield(); } } listOfTasks.Add(localFunc()); } } } "; var comp = CreateCompilationWithMscorlib46(source); comp.VerifyDiagnostics( // (16,21): error CS1996: Cannot await in the body of a lock statement // await Task.Yield(); Diagnostic(ErrorCode.ERR_BadAwaitInLock, "await Task.Yield()").WithLocation(16, 21)); } [ConditionalFact(typeof(DesktopOnly))] public void LocalFunctionDoesNotOverwriteInnerTryCatchFinallyScopeFlags() { var source = @" using System; using System.Collections.Generic; class C { void M() { try { IEnumerable<int> localFunc() { try { yield return 1; } catch (Exception) {} } localFunc(); } catch (Exception) { IEnumerable<int> localFunc() { try {} catch (Exception) { yield return 2; } } localFunc(); } finally { IEnumerable<int> localFunc() { try {} finally { yield return 3; } } localFunc(); } } } "; var comp = CreateCompilationWithMscorlib46(source); comp.VerifyDiagnostics( // (15,21): error CS1626: Cannot yield a value in the body of a try block with a catch clause // yield return 1; Diagnostic(ErrorCode.ERR_BadYieldInTryOfCatch, "yield").WithLocation(15, 21), // (29,21): error CS1631: Cannot yield a value in the body of a catch clause // yield return 2; Diagnostic(ErrorCode.ERR_BadYieldInCatch, "yield").WithLocation(29, 21), // (42,21): error CS1625: Cannot yield in the body of a finally clause // yield return 3; Diagnostic(ErrorCode.ERR_BadYieldInFinally, "yield").WithLocation(42, 21)); } [ConditionalFact(typeof(DesktopOnly))] public void RethrowingExceptionsInCatchInsideLocalFuncIsAllowed() { var source = @" using System; class C { static void Main() { try { throw new Exception(); } catch (Exception) { void localFunc() { try { throw new Exception(); } catch (Exception) { Console.Write(""localFunc""); throw; } } try { localFunc(); } catch (Exception) { Console.Write(""_thrown""); } } } } "; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "localFunc_thrown"); } [ConditionalFact(typeof(DesktopOnly))] public void RethrowingExceptionsInLocalFuncInsideCatchIsNotAllowed() { var source = @" using System; class C { static void Main() { try {} catch (Exception) { void localFunc() { throw; } localFunc(); } } } "; var comp = CreateCompilationWithMscorlib46(source); comp.VerifyDiagnostics( // (13,17): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause // throw; Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw").WithLocation(13, 17)); } [Fact] public void LocalFunctionTypeParametersUseCorrectBinder() { var text = @" class C { static void M() { void local<[X]T>() {} } }"; var tree = SyntaxFactory.ParseSyntaxTree(text, options: TestOptions.Regular9); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree, ignoreAccessibility: true); var newTree = SyntaxFactory.ParseSyntaxTree(text + " "); var m = newTree.GetRoot() .DescendantNodes().OfType<MethodDeclarationSyntax>().Single(); Assert.True(model.TryGetSpeculativeSemanticModelForMethodBody(m.Body.SpanStart, m, out model)); var x = newTree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Single(); Assert.Equal("X", x.Identifier.Text); // If we aren't using the right binder here, the compiler crashes going through the binder factory var info = model.GetSymbolInfo(x); Assert.Null(info.Symbol); comp.VerifyDiagnostics( // (6,21): error CS0246: The type or namespace name 'XAttribute' could not be found (are you missing a using directive or an assembly reference?) // void local<[X]T>() {} Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "X").WithArguments("XAttribute").WithLocation(6, 21), // (6,21): error CS0246: The type or namespace name 'X' could not be found (are you missing a using directive or an assembly reference?) // void local<[X]T>() {} Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "X").WithArguments("X").WithLocation(6, 21), // (6,14): warning CS8321: The local function 'local' is declared but never used // void local<[X]T>() {} Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local").WithArguments("local").WithLocation(6, 14)); } [Theory] [InlineData("[A] void local() { }")] [InlineData("[return: A] void local() { }")] [InlineData("void local([A] int i) { }")] [InlineData("void local<[A]T>() {}")] [InlineData("[A] int x = 123;")] public void LocalFunctionAttribute_SpeculativeSemanticModel(string statement) { string text = $@" using System; class A : Attribute {{}} class C {{ static void M() {{ {statement} }} }}"; var tree = SyntaxFactory.ParseSyntaxTree(text); var comp = (Compilation)CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var a = tree.GetRoot().DescendantNodes() .OfType<IdentifierNameSyntax>().ElementAt(2); Assert.Equal("A", a.Identifier.Text); var attrInfo = model.GetSymbolInfo(a); var attrType = comp.GlobalNamespace.GetTypeMember("A"); var attrCtor = attrType.GetMember(".ctor"); Assert.Equal(attrCtor, attrInfo.Symbol); // Assert that this is also true for the speculative semantic model var newTree = SyntaxFactory.ParseSyntaxTree(text + " "); var m = newTree.GetRoot() .DescendantNodes().OfType<MethodDeclarationSyntax>().Single(); Assert.True(model.TryGetSpeculativeSemanticModelForMethodBody(m.Body.SpanStart, m, out model)); a = newTree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().ElementAt(2); Assert.Equal("A", a.Identifier.Text); // If we aren't using the right binder here, the compiler crashes going through the binder factory var info = model.GetSymbolInfo(a); // This behavior is wrong. See https://github.com/dotnet/roslyn/issues/24135 Assert.Equal(attrType, info.Symbol); } [Theory] [InlineData(@"[Attr(42, Name = ""hello"")] void local() { }")] [InlineData(@"[return: Attr(42, Name = ""hello"")] void local() { }")] [InlineData(@"void local([Attr(42, Name = ""hello"")] int i) { }")] [InlineData(@"void local<[Attr(42, Name = ""hello"")]T>() {}")] [InlineData(@"[Attr(42, Name = ""hello"")] int x = 123;")] public void LocalFunctionAttribute_Argument_SemanticModel(string statement) { var text = $@" class Attr {{ public Attr(int id) {{ }} public string Name {{ get; set; }} }} class C {{ static void M() {{ {statement} }} }}"; var tree = SyntaxFactory.ParseSyntaxTree(text, options: TestOptions.Regular9); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree, ignoreAccessibility: true); validate(model, tree); var newTree = SyntaxFactory.ParseSyntaxTree(text + " ", options: TestOptions.Regular9); var mMethod = (MethodDeclarationSyntax)newTree.FindNodeOrTokenByKind(SyntaxKind.MethodDeclaration, occurrence: 1).AsNode(); Assert.True(model.TryGetSpeculativeSemanticModelForMethodBody(mMethod.Body.SpanStart, mMethod, out var newModel)); validate(newModel, newTree); static void validate(SemanticModel model, SyntaxTree tree) { var attributeSyntax = tree.GetRoot().DescendantNodes().OfType<AttributeSyntax>().Single(); var attrArgs = attributeSyntax.ArgumentList.Arguments; var attrArg0 = attrArgs[0].Expression; Assert.Null(model.GetSymbolInfo(attrArg0).Symbol); var argType0 = model.GetTypeInfo(attrArg0).Type; Assert.Equal(SpecialType.System_Int32, argType0.SpecialType); var attrArg1 = attrArgs[1].Expression; Assert.Null(model.GetSymbolInfo(attrArg1).Symbol); var argType1 = model.GetTypeInfo(attrArg1).Type; Assert.Equal(SpecialType.System_String, argType1.SpecialType); } } [Fact] public void LocalFunctionAttribute_OnFunction() { const string text = @" using System; class A : Attribute { } class C { void M() { [A] void local() { } } } "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (10,14): warning CS8321: The local function 'local' is declared but never used // void local() { } Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local").WithArguments("local").WithLocation(10, 14)); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var localFunction = tree.GetRoot().DescendantNodes() .OfType<LocalFunctionStatementSyntax>() .Single(); var attributeList = localFunction.AttributeLists.Single(); Assert.Null(attributeList.Target); var attribute = attributeList.Attributes.Single(); Assert.Equal("A", ((SimpleNameSyntax)attribute.Name).Identifier.ValueText); var symbol = (IMethodSymbol)model.GetDeclaredSymbol(localFunction); Assert.NotNull(symbol); var attributes = symbol.GetAttributes().As<CSharpAttributeData>(); Assert.Equal(new[] { "A" }, GetAttributeNames(attributes)); var returnAttributes = symbol.GetReturnTypeAttributes(); Assert.Empty(returnAttributes); } [Fact] public void LocalFunctionAttribute_OnFunction_Argument() { const string text = @" using System; class A : Attribute { internal A(int i) { } } class C { void M() { [A(42)] void local() { } } } "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (13,14): warning CS8321: The local function 'local' is declared but never used // void local() { } Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local").WithArguments("local").WithLocation(13, 14)); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var localFunction = tree.GetRoot().DescendantNodes() .OfType<LocalFunctionStatementSyntax>() .Single(); var attributeList = localFunction.AttributeLists.Single(); Assert.Null(attributeList.Target); var attribute = attributeList.Attributes.Single(); Assert.Equal("A", ((SimpleNameSyntax)attribute.Name).Identifier.ValueText); var symbol = (IMethodSymbol)model.GetDeclaredSymbol(localFunction); Assert.NotNull(symbol); var attributes = symbol.GetAttributes(); var attributeData = attributes.Single(); var aAttribute = comp.GetTypeByMetadataName("A"); Assert.Equal(aAttribute, attributeData.AttributeClass.GetSymbol()); Assert.Equal(aAttribute.InstanceConstructors.Single(), attributeData.AttributeConstructor.GetSymbol()); Assert.Equal(42, attributeData.ConstructorArguments.Single().Value); var returnAttributes = symbol.GetReturnTypeAttributes(); Assert.Empty(returnAttributes); } [Fact] public void LocalFunctionAttribute_OnFunction_LocalArgument() { const string text = @" using System; class A : Attribute { internal A(string s) { } } class C { void M() { #pragma warning disable 0219 // Unreferenced local variable string s1 = ""hello""; const string s2 = ""world""; #pragma warning disable 8321 // Unreferenced local function [A(s1)] // 1 void local1() { } [A(nameof(s1))] void local2() { } [A(s2)] void local3() { } [A(s1.ToString())] // 2 void local4() { } static string local5() => ""hello""; [A(local5())] // 3 void local6() { } } } "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (17,12): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(s1)] // 1 Diagnostic(ErrorCode.ERR_BadAttributeArgument, "s1").WithLocation(17, 12), // (26,12): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(s1.ToString())] // 2 Diagnostic(ErrorCode.ERR_BadAttributeArgument, "s1.ToString()").WithLocation(26, 12), // (31,12): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(local5())] // 3 Diagnostic(ErrorCode.ERR_BadAttributeArgument, "local5()").WithLocation(31, 12)); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var arg1 = (AttributeArgumentSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.AttributeArgument, occurrence: 1).AsNode(); Assert.Equal("System.String s1", model.GetSymbolInfo(arg1.Expression).Symbol.ToTestDisplayString()); Assert.Equal(SpecialType.System_String, model.GetTypeInfo(arg1.Expression).Type.SpecialType); var arg2 = (AttributeArgumentSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.AttributeArgument, occurrence: 2).AsNode(); Assert.Null(model.GetSymbolInfo(arg2.Expression).Symbol); Assert.Equal(SpecialType.System_String, model.GetTypeInfo(arg2.Expression).Type.SpecialType); var arg3 = (AttributeArgumentSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.AttributeArgument, occurrence: 3).AsNode(); Assert.Equal("System.String s2", model.GetSymbolInfo(arg3.Expression).Symbol.ToTestDisplayString()); Assert.Equal(SpecialType.System_String, model.GetTypeInfo(arg3.Expression).Type.SpecialType); } [Fact] public void LocalFunctionAttribute_OnFunction_DeclarationPattern() { const string text = @" using System; class A : Attribute { internal A(bool b) { } } class C { void M() { #pragma warning disable 8321 // Unreferenced local function [A(42 is int i)] // 1 void local1() { _ = i.ToString(); // 2 } _ = i.ToString(); // 3 } } "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (13,12): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(42 is int i)] // 1 Diagnostic(ErrorCode.ERR_BadAttributeArgument, "42 is int i").WithLocation(13, 12), // (16,17): error CS0103: The name 'i' does not exist in the current context // _ = i.ToString(); // 2 Diagnostic(ErrorCode.ERR_NameNotInContext, "i").WithArguments("i").WithLocation(16, 17), // (19,13): error CS0103: The name 'i' does not exist in the current context // _ = i.ToString(); // 3 Diagnostic(ErrorCode.ERR_NameNotInContext, "i").WithArguments("i").WithLocation(19, 13)); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var arg = (AttributeArgumentSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.AttributeArgument, occurrence: 1).AsNode(); Assert.Null(model.GetSymbolInfo(arg.Expression).Symbol); Assert.Equal(SpecialType.System_Boolean, model.GetTypeInfo(arg.Expression).Type.SpecialType); var decl = (DeclarationPatternSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.DeclarationPattern, occurrence: 1).AsNode(); Assert.Equal("System.Int32 i", model.GetDeclaredSymbol(decl.Designation).ToTestDisplayString()); } [Fact] public void LocalFunctionAttribute_OnFunction_OutVarInCall() { const string text = @" using System; class A : Attribute { internal A(bool b) { } } class C { void M1() { #pragma warning disable 8321 // Unreferenced local function [A(M2(out var i))] // 1 void local1() { _ = i.ToString(); // 2 } _ = i.ToString(); // 3 } static bool M2(out int x) { x = 0; return false; } } "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (13,12): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(M2(out var i))] // 1 Diagnostic(ErrorCode.ERR_BadAttributeArgument, "M2(out var i)").WithLocation(13, 12), // (16,17): error CS0103: The name 'i' does not exist in the current context // _ = i.ToString(); // 2 Diagnostic(ErrorCode.ERR_NameNotInContext, "i").WithArguments("i").WithLocation(16, 17), // (19,13): error CS0103: The name 'i' does not exist in the current context // _ = i.ToString(); // 3 Diagnostic(ErrorCode.ERR_NameNotInContext, "i").WithArguments("i").WithLocation(19, 13)); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var arg = (AttributeArgumentSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.AttributeArgument, occurrence: 1).AsNode(); Assert.Equal("System.Boolean C.M2(out System.Int32 x)", model.GetSymbolInfo(arg.Expression).Symbol.ToTestDisplayString()); Assert.Equal(SpecialType.System_Boolean, model.GetTypeInfo(arg.Expression).Type.SpecialType); var decl = (DeclarationExpressionSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.DeclarationExpression, occurrence: 1).AsNode(); Assert.Equal("System.Int32 i", model.GetDeclaredSymbol(decl.Designation).ToTestDisplayString()); } [Fact] public void LocalFunctionAttribute_OutParam() { const string text = @" using System; class A : Attribute { internal A(out string s) { s = ""a""; } } class C { void M() { #pragma warning disable 8321, 0168 // Unreferenced local string s; [A(out s)] void local1() { } [A(out var s)] void local2() { } } } "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (15,12): error CS1041: Identifier expected; 'out' is a keyword // [A(out s)] Diagnostic(ErrorCode.ERR_IdentifierExpectedKW, "out").WithArguments("", "out").WithLocation(15, 12), // (15,16): error CS1620: Argument 1 must be passed with the 'out' keyword // [A(out s)] Diagnostic(ErrorCode.ERR_BadArgRef, "s").WithArguments("1", "out").WithLocation(15, 16), // (18,10): error CS1729: 'A' does not contain a constructor that takes 2 arguments // [A(out var s)] Diagnostic(ErrorCode.ERR_BadCtorArgCount, "A(out var s)").WithArguments("A", "2").WithLocation(18, 10), // (18,12): error CS1041: Identifier expected; 'out' is a keyword // [A(out var s)] Diagnostic(ErrorCode.ERR_IdentifierExpectedKW, "out").WithArguments("", "out").WithLocation(18, 12), // (18,16): error CS0103: The name 'var' does not exist in the current context // [A(out var s)] Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(18, 16), // (18,20): error CS1003: Syntax error, ',' expected // [A(out var s)] Diagnostic(ErrorCode.ERR_SyntaxError, "s").WithArguments(",", "").WithLocation(18, 20)); } [Fact] public void LocalFunctionAttribute_Return() { const string text = @" using System; class A : Attribute { } class C { void M() { [return: A] int local() => 42; } } "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (10,13): warning CS8321: The local function 'local' is declared but never used // int local() => 42; Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local").WithArguments("local").WithLocation(10, 13)); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var localFunction = tree.GetRoot().DescendantNodes() .OfType<LocalFunctionStatementSyntax>() .Single(); var attributeList = localFunction.AttributeLists.Single(); Assert.Equal(SyntaxKind.ReturnKeyword, attributeList.Target.Identifier.Kind()); var attribute = attributeList.Attributes.Single(); Assert.Equal("A", ((SimpleNameSyntax)attribute.Name).Identifier.ValueText); var symbol = (IMethodSymbol)model.GetDeclaredSymbol(localFunction); Assert.NotNull(symbol); var returnAttributes = symbol.GetReturnTypeAttributes(); var attributeData = returnAttributes.Single(); var aAttribute = comp.GetTypeByMetadataName("A"); Assert.Equal(aAttribute, attributeData.AttributeClass.GetSymbol()); Assert.Equal(aAttribute.InstanceConstructors.Single(), attributeData.AttributeConstructor.GetSymbol()); var attributes = symbol.GetAttributes(); Assert.Empty(attributes); } [Fact] public void LocalFunctionAttribute_Parameter() { var source = @" using System; class A : Attribute { } class C { void M() { int local([A] int i) => i; } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,13): warning CS8321: The local function 'local' is declared but never used // int local([A] int i) => i; Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local").WithArguments("local").WithLocation(9, 13)); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var localFunction = tree.GetRoot().DescendantNodes().OfType<LocalFunctionStatementSyntax>().Single(); var parameter = localFunction.ParameterList.Parameters.Single(); var paramSymbol = model.GetDeclaredSymbol(parameter); var attrs = paramSymbol.GetAttributes(); var attr = attrs.Single(); Assert.Equal(comp.GetTypeByMetadataName("A"), attr.AttributeClass.GetSymbol()); } [Fact] public void LocalFunctionAttribute_LangVersionError() { const string text = @" using System; class A : Attribute { } class C { void M() { #pragma warning disable 8321 // Unreferenced local function [A] void local1() { } [return: A] void local2() { } void local3([A] int i) { } void local4<[A] T>() { } } } "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (10,9): error CS8400: Feature 'local function attributes' is not available in C# 8.0. Please use language version 9.0 or greater. // [A] Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "[A]").WithArguments("local function attributes", "9.0").WithLocation(10, 9), // (13,9): error CS8400: Feature 'local function attributes' is not available in C# 8.0. Please use language version 9.0 or greater. // [return: A] Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "[return: A]").WithArguments("local function attributes", "9.0").WithLocation(13, 9), // (16,21): error CS8400: Feature 'local function attributes' is not available in C# 8.0. Please use language version 9.0 or greater. // void local3([A] int i) { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "[A]").WithArguments("local function attributes", "9.0").WithLocation(16, 21), // (18,21): error CS8400: Feature 'local function attributes' is not available in C# 8.0. Please use language version 9.0 or greater. // void local4<[A] T>() { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "[A]").WithArguments("local function attributes", "9.0").WithLocation(18, 21)); comp = CreateCompilation(text, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); } [Fact] public void LocalFunctionAttribute_BadAttributeLocation() { const string text = @" using System; [AttributeUsage(AttributeTargets.Property)] class PropAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method)] class MethodAttribute : Attribute { } [AttributeUsage(AttributeTargets.ReturnValue)] class ReturnAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter)] class ParamAttribute : Attribute { } [AttributeUsage(AttributeTargets.GenericParameter)] class TypeParamAttribute : Attribute { } public class C { public void M() { #pragma warning disable 8321 // Unreferenced local function [Prop] // 1 [Return] // 2 [Method] [return: Prop] // 3 [return: Return] [return: Method] // 4 void local< [Param] // 5 [TypeParam] T>( [Param] [TypeParam] // 6 T t) { } } } "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (22,10): error CS0592: Attribute 'Prop' is not valid on this declaration type. It is only valid on 'property, indexer' declarations. // [Prop] // 1 Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "Prop").WithArguments("Prop", "property, indexer").WithLocation(22, 10), // (23,10): error CS0592: Attribute 'Return' is not valid on this declaration type. It is only valid on 'return' declarations. // [Return] // 2 Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "Return").WithArguments("Return", "return").WithLocation(23, 10), // (25,18): error CS0592: Attribute 'Prop' is not valid on this declaration type. It is only valid on 'property, indexer' declarations. // [return: Prop] // 3 Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "Prop").WithArguments("Prop", "property, indexer").WithLocation(25, 18), // (27,18): error CS0592: Attribute 'Method' is not valid on this declaration type. It is only valid on 'method' declarations. // [return: Method] // 4 Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "Method").WithArguments("Method", "method").WithLocation(27, 18), // (29,14): error CS0592: Attribute 'Param' is not valid on this declaration type. It is only valid on 'parameter' declarations. // [Param] // 5 Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "Param").WithArguments("Param", "parameter").WithLocation(29, 14), // (33,14): error CS0592: Attribute 'TypeParam' is not valid on this declaration type. It is only valid on 'type parameter' declarations. // [TypeParam] // 6 Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "TypeParam").WithArguments("TypeParam", "type parameter").WithLocation(33, 14)); var tree = comp.SyntaxTrees.Single(); var localFunction = tree.GetRoot().DescendantNodes().OfType<LocalFunctionStatementSyntax>().Single(); var model = comp.GetSemanticModel(tree); var symbol = (IMethodSymbol)model.GetDeclaredSymbol(localFunction); Assert.NotNull(symbol); var attributes = symbol.GetAttributes(); Assert.Equal(3, attributes.Length); Assert.Equal(comp.GetTypeByMetadataName("PropAttribute"), attributes[0].AttributeClass.GetSymbol()); Assert.Equal(comp.GetTypeByMetadataName("ReturnAttribute"), attributes[1].AttributeClass.GetSymbol()); Assert.Equal(comp.GetTypeByMetadataName("MethodAttribute"), attributes[2].AttributeClass.GetSymbol()); var returnAttributes = symbol.GetReturnTypeAttributes(); Assert.Equal(3, returnAttributes.Length); Assert.Equal(comp.GetTypeByMetadataName("PropAttribute"), returnAttributes[0].AttributeClass.GetSymbol()); Assert.Equal(comp.GetTypeByMetadataName("ReturnAttribute"), returnAttributes[1].AttributeClass.GetSymbol()); Assert.Equal(comp.GetTypeByMetadataName("MethodAttribute"), returnAttributes[2].AttributeClass.GetSymbol()); } [Fact] public void LocalFunctionAttribute_AttributeSemanticModel() { const string text = @" using System; class A : Attribute { } class C { void M() { local1(); local2(); local3(0); local4<object>(); [A] void local1() { } [return: A] void local2() { } void local3([A] int i) { } void local4<[A] T>() { } } } "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var attributeSyntaxes = tree.GetRoot().DescendantNodes().OfType<AttributeSyntax>().ToList(); Assert.Equal(4, attributeSyntaxes.Count); var attributeConstructor = comp.GetTypeByMetadataName("A").InstanceConstructors.Single(); foreach (var attributeSyntax in attributeSyntaxes) { var symbol = model.GetSymbolInfo(attributeSyntax).Symbol.GetSymbol<MethodSymbol>(); Assert.Equal(attributeConstructor, symbol); } } [Fact] public void StatementAttributeSemanticModel() { const string text = @" using System; class A : Attribute { } class C { void M() { #pragma warning disable 219 // The variable '{0}' is assigned but its value is never used [A] int i = 0; } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (11,9): error CS7014: Attributes are not valid in this context. // [A] int i = 0; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(11, 9)); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var attrSyntax = tree.GetRoot().DescendantNodes().OfType<AttributeSyntax>().Single(); var attrConstructor = (IMethodSymbol)model.GetSymbolInfo(attrSyntax).Symbol; Assert.Equal(MethodKind.Constructor, attrConstructor.MethodKind); Assert.Equal("A", attrConstructor.ContainingType.Name); } [Fact] public void LocalFunctionNoBody() { const string text = @" class C { void M() { local1(); void local1(); } } "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,14): error CS8112: Local function 'local1()' must either have a body or be marked 'static extern'. // void local1(); Diagnostic(ErrorCode.ERR_LocalFunctionMissingBody, "local1").WithArguments("local1()").WithLocation(8, 14)); } [Fact] public void LocalFunctionExtern() { const string text = @" using System.Runtime.InteropServices; class C { void M() { #pragma warning disable 8321 // Unreferenced local function [DllImport(""a"")] extern void local1(); // 1, 2 [DllImport(""a"")] extern void local2() { } // 3, 4 [DllImport(""a"")] extern int local3() => 0; // 5, 6 static void local4(); // 7 static void local5() { } static int local6() => 0; [DllImport(""a"")] static extern void local7(); [DllImport(""a"")] static extern void local8() { } // 8 [DllImport(""a"")] static extern int local9() => 0; // 9 [DllImport(""a"")] extern static void local10(); [DllImport(""a"")] extern static void local11() { } // 10 [DllImport(""a"")] extern static int local12() => 0; // 11 } } "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (10,10): error CS0601: The DllImport attribute must be specified on a method marked 'static' and 'extern' // [DllImport("a")] extern void local1(); // 1, 2 Diagnostic(ErrorCode.ERR_DllImportOnInvalidMethod, "DllImport").WithLocation(10, 10), // (10,38): error CS8112: Local function 'local1()' must either have a body or be marked 'static extern'. // [DllImport("a")] extern void local1(); // 1, 2 Diagnostic(ErrorCode.ERR_LocalFunctionMissingBody, "local1").WithArguments("local1()").WithLocation(10, 38), // (11,10): error CS0601: The DllImport attribute must be specified on a method marked 'static' and 'extern' // [DllImport("a")] extern void local2() { } // 3, 4 Diagnostic(ErrorCode.ERR_DllImportOnInvalidMethod, "DllImport").WithLocation(11, 10), // (11,38): error CS0179: 'local2()' cannot be extern and declare a body // [DllImport("a")] extern void local2() { } // 3, 4 Diagnostic(ErrorCode.ERR_ExternHasBody, "local2").WithArguments("local2()").WithLocation(11, 38), // (12,10): error CS0601: The DllImport attribute must be specified on a method marked 'static' and 'extern' // [DllImport("a")] extern int local3() => 0; // 5, 6 Diagnostic(ErrorCode.ERR_DllImportOnInvalidMethod, "DllImport").WithLocation(12, 10), // (12,37): error CS0179: 'local3()' cannot be extern and declare a body // [DllImport("a")] extern int local3() => 0; // 5, 6 Diagnostic(ErrorCode.ERR_ExternHasBody, "local3").WithArguments("local3()").WithLocation(12, 37), // (14,21): error CS8112: Local function 'local4()' must either have a body or be marked 'static extern'. // static void local4(); // 7 Diagnostic(ErrorCode.ERR_LocalFunctionMissingBody, "local4").WithArguments("local4()").WithLocation(14, 21), // (19,45): error CS0179: 'local8()' cannot be extern and declare a body // [DllImport("a")] static extern void local8() { } // 8 Diagnostic(ErrorCode.ERR_ExternHasBody, "local8").WithArguments("local8()").WithLocation(19, 45), // (20,44): error CS0179: 'local9()' cannot be extern and declare a body // [DllImport("a")] static extern int local9() => 0; // 9 Diagnostic(ErrorCode.ERR_ExternHasBody, "local9").WithArguments("local9()").WithLocation(20, 44), // (23,45): error CS0179: 'local11()' cannot be extern and declare a body // [DllImport("a")] extern static void local11() { } // 10 Diagnostic(ErrorCode.ERR_ExternHasBody, "local11").WithArguments("local11()").WithLocation(23, 45), // (24,44): error CS0179: 'local12()' cannot be extern and declare a body // [DllImport("a")] extern static int local12() => 0; // 11 Diagnostic(ErrorCode.ERR_ExternHasBody, "local12").WithArguments("local12()").WithLocation(24, 44)); } [Fact] public void LocalFunctionExtern_Generic() { var source = @" using System; using System.Runtime.InteropServices; class C { #pragma warning disable 8321 // Unreferenced local function void M() { [DllImport(""a"")] extern static void local1(); [DllImport(""a"")] extern static void local2<T>(); // 1 void local3() { [DllImport(""a"")] extern static void local1(); [DllImport(""a"")] extern static void local2<T2>(); // 2 } void local4<T4>() { [DllImport(""a"")] extern static void local1(); // 3 [DllImport(""a"")] extern static void local2<T2>(); // 4 } Action a = () => { [DllImport(""a"")] extern static void local1(); [DllImport(""a"")] extern static void local2<T>(); // 5 void local3() { [DllImport(""a"")] extern static void local1(); [DllImport(""a"")] extern static void local2<T2>(); // 6 } void local4<T4>() { [DllImport(""a"")] extern static void local1(); // 7 [DllImport(""a"")] extern static void local2<T2>(); // 8 } }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (12,10): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type. // [DllImport("a")] extern static void local2<T>(); // 1 Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(12, 10), // (17,14): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type. // [DllImport("a")] extern static void local2<T2>(); // 2 Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(17, 14), // (22,14): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type. // [DllImport("a")] extern static void local1(); // 3 Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(22, 14), // (23,14): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type. // [DllImport("a")] extern static void local2<T2>(); // 4 Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(23, 14), // (29,14): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type. // [DllImport("a")] extern static void local2<T>(); // 5 Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(29, 14), // (34,18): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type. // [DllImport("a")] extern static void local2<T2>(); // 6 Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(34, 18), // (39,18): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type. // [DllImport("a")] extern static void local1(); // 7 Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(39, 18), // (40,18): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type. // [DllImport("a")] extern static void local2<T2>(); // 8 Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(40, 18)); } [Theory] [InlineData("<CT>", "", "")] [InlineData("", "<MT>", "")] [InlineData("", "", "<LT>")] public void LocalFunctionExtern_Generic_GenericMembers(string classTypeParams, string methodTypeParams, string localFunctionTypeParams) { var source = $@" using System; using System.Runtime.InteropServices; class C{classTypeParams} {{ #pragma warning disable 8321 // Unreferenced local function void M{methodTypeParams}() {{ void localOuter{localFunctionTypeParams}() {{ [DllImport(""a"")] extern static void local1(); // 1 [DllImport(""a"")] extern static void local2<T>(); // 2 void local3() {{ [DllImport(""a"")] extern static void local1(); // 3 [DllImport(""a"")] extern static void local2<T2>(); // 4 }} void local4<T4>() {{ [DllImport(""a"")] extern static void local1(); // 5 [DllImport(""a"")] extern static void local2<T2>(); // 6 }} Action a = () => {{ [DllImport(""a"")] extern static void local1(); // 7 [DllImport(""a"")] extern static void local2<T>(); // 8 void local3() {{ [DllImport(""a"")] extern static void local1(); // 9 [DllImport(""a"")] extern static void local2<T2>(); // 10 }} void local4<T4>() {{ [DllImport(""a"")] extern static void local1(); // 11 [DllImport(""a"")] extern static void local2<T2>(); // 12 }} }}; }} }} }}"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (13,14): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type. // [DllImport("a")] extern static void local1(); // 1 Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(13, 14), // (14,14): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type. // [DllImport("a")] extern static void local2<T>(); // 2 Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(14, 14), // (18,18): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type. // [DllImport("a")] extern static void local1(); // 3 Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(18, 18), // (19,18): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type. // [DllImport("a")] extern static void local2<T2>(); // 4 Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(19, 18), // (24,18): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type. // [DllImport("a")] extern static void local1(); // 5 Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(24, 18), // (25,18): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type. // [DllImport("a")] extern static void local2<T2>(); // 6 Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(25, 18), // (30,18): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type. // [DllImport("a")] extern static void local1(); // 7 Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(30, 18), // (31,18): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type. // [DllImport("a")] extern static void local2<T>(); // 8 Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(31, 18), // (35,22): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type. // [DllImport("a")] extern static void local1(); // 9 Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(35, 22), // (36,22): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type. // [DllImport("a")] extern static void local2<T2>(); // 10 Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(36, 22), // (41,22): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type. // [DllImport("a")] extern static void local1(); // 11 Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(41, 22), // (42,22): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type. // [DllImport("a")] extern static void local2<T2>(); // 12 Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(42, 22)); } [Fact] public void LocalFunctionExtern_NoImplementationWarning_Attribute() { const string text = @" using System.Runtime.InteropServices; class Attr : System.Attribute { } class C { void M() { #pragma warning disable 8321 // Unreferenced local function static extern void local1(); // 1 static extern void local2() { } // 2 [DllImport(""a"")] static extern void local3(); [Attr] static extern void local4(); } } "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (12,28): warning CS0626: Method, operator, or accessor 'local1()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // static extern void local1(); // 1 Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "local1").WithArguments("local1()").WithLocation(12, 28), // (13,28): error CS0179: 'local2()' cannot be extern and declare a body // static extern void local2() { } // 2 Diagnostic(ErrorCode.ERR_ExternHasBody, "local2").WithArguments("local2()").WithLocation(13, 28)); } [Fact] public void LocalFunctionExtern_Errors() { const string text = @" class C { #pragma warning disable 8321 // Unreferenced local function void M1() { void local1(); // 1 static extern void local1(); // 2, 3 } void M2() { void local1(); // 4 static extern void local1() { } // 5 } } "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,14): error CS8112: Local function 'local1()' must either have a body or be marked 'static extern'. // void local1(); // 1 Diagnostic(ErrorCode.ERR_LocalFunctionMissingBody, "local1").WithArguments("local1()").WithLocation(8, 14), // (9,28): error CS0128: A local variable or function named 'local1' is already defined in this scope // static extern void local1(); // 2, 3 Diagnostic(ErrorCode.ERR_LocalDuplicate, "local1").WithArguments("local1").WithLocation(9, 28), // (9,28): warning CS0626: Method, operator, or accessor 'local1()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // static extern void local1(); // 2, 3 Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "local1").WithArguments("local1()").WithLocation(9, 28), // (14,14): error CS8112: Local function 'local1()' must either have a body or be marked 'static extern'. // void local1(); // 4 Diagnostic(ErrorCode.ERR_LocalFunctionMissingBody, "local1").WithArguments("local1()").WithLocation(14, 14), // (15,28): error CS0128: A local variable or function named 'local1' is already defined in this scope // static extern void local1() { } // 5 Diagnostic(ErrorCode.ERR_LocalDuplicate, "local1").WithArguments("local1").WithLocation(15, 28)); } [Fact] public void ComImport_Class() { const string text = @" using System; using System.Runtime.InteropServices; [ComImport, Guid(""00020813-0000-0000-c000-000000000046"")] class C { void M() // 1 { #pragma warning disable 8321 // Unreferenced local function void local1() { } } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (8,10): error CS0423: Since 'C' has the ComImport attribute, 'C.M()' must be extern or abstract // void M() // 1 Diagnostic(ErrorCode.ERR_ComImportWithImpl, "M").WithArguments("C.M()", "C").WithLocation(8, 10)); } [Fact] public void UnsafeLocal() { var source = @" class C { void M() { var bytesA = local(); unsafe byte[] local() { var bytes = new byte[sizeof(int)]; fixed (byte* ptr = &bytes[0]) { *(int*)ptr = sizeof(int); } return bytes; } } }"; var comp = CreateCompilation(source); Assert.Empty(comp.GetDeclarationDiagnostics()); comp.VerifyDiagnostics( // (8,23): error CS0227: Unsafe code may only appear if compiling with /unsafe // unsafe byte[] local() Diagnostic(ErrorCode.ERR_IllegalUnsafe, "local").WithLocation(8, 23) ); var compWithUnsafe = CreateCompilation(source, options: TestOptions.UnsafeDebugDll); compWithUnsafe.VerifyDiagnostics(); } [Fact] public void LocalInUnsafeStruct() { var source = @" unsafe struct C { void A() { var bytesA = local(); var bytesB = B(); byte[] local() { var bytes = new byte[sizeof(int)]; fixed (byte* ptr = &bytes[0]) { *(int*)ptr = sizeof(int); } return bytes; } } byte[] B() { var bytes = new byte[sizeof(long)]; fixed (byte* ptr = &bytes[0]) { *(long*)ptr = sizeof(long); } return bytes; } }"; // no need to declare local function `local` or method `B` as unsafe var compWithUnsafe = CreateCompilation(source, options: TestOptions.UnsafeDebugDll); compWithUnsafe.VerifyDiagnostics(); } [Fact] public void LocalInUnsafeBlock() { var source = @" struct C { void A() { unsafe { var bytesA = local(); byte[] local() { var bytes = new byte[sizeof(int)]; fixed (byte* ptr = &bytes[0]) { *(int*)ptr = sizeof(int); } return bytes; } } } }"; // no need to declare local function `local` as unsafe var compWithUnsafe = CreateCompilation(source, options: TestOptions.UnsafeDebugDll); compWithUnsafe.VerifyDiagnostics(); } [Fact] public void ConstraintBinding() { var comp = CreateCompilation(@" class C { void M() { void Local<T, U>() where T : U where U : class { } Local<object, object>(); } }"); comp.VerifyDiagnostics(); } [Fact] public void ConstraintBinding2() { var comp = CreateCompilation(@" class C { void M() { void Local<T, U>(T t) where T : U where U : t { } Local<object, object>(null); } }"); comp.VerifyDiagnostics( // (8,23): error CS0246: The type or namespace name 't' could not be found (are you missing a using directive or an assembly reference?) // where U : t Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "t").WithArguments("t").WithLocation(8, 23), // (11,9): error CS0311: The type 'object' cannot be used as type parameter 'U' in the generic type or method 'Local<T, U>(T)'. There is no implicit reference conversion from 'object' to 't'. // Local<object, object>(null); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "Local<object, object>").WithArguments("Local<T, U>(T)", "t", "U", "object").WithLocation(11, 9)); } [Fact] [WorkItem(17014, "https://github.com/dotnet/roslyn/pull/17014")] public void RecursiveLocalFuncsAsParameterTypes() { var comp = CreateCompilation(@" class C { void M() { int L(L2 l2) => 0; int L2(L l1) => 0; } }"); comp.VerifyDiagnostics( // (6,15): error CS0246: The type or namespace name 'L2' could not be found (are you missing a using directive or an assembly reference?) // int L(L2 l2) => 0; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "L2").WithArguments("L2").WithLocation(6, 15), // (7,16): error CS0246: The type or namespace name 'L' could not be found (are you missing a using directive or an assembly reference?) // int L2(L l1) => 0; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "L").WithArguments("L").WithLocation(7, 16), // (6,13): warning CS8321: The local function 'L' is declared but never used // int L(L2 l2) => 0; Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "L").WithArguments("L").WithLocation(6, 13), // (7,13): warning CS8321: The local function 'L2' is declared but never used // int L2(L l1) => 0; Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "L2").WithArguments("L2").WithLocation(7, 13)); } [Fact] [WorkItem(16451, "https://github.com/dotnet/roslyn/issues/16451")] public void BadGenericConstraint() { var comp = CreateCompilation(@" class C { public void M<T>(T value) where T : class, object { } }"); comp.VerifyDiagnostics( // (4,48): error CS0702: Constraint cannot be special class 'object' // public void M<T>(T value) where T : class, object { } Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object").WithArguments("object").WithLocation(4, 48) ); } [Fact] [WorkItem(16451, "https://github.com/dotnet/roslyn/issues/16451")] public void RecursiveDefaultParameter() { var comp = CreateCompilation(@" class C { public static void Main() { int Local(int j = Local()) => 0; Local(); } }"); comp.VerifyDiagnostics( // (6,27): error CS1736: Default parameter value for 'j' must be a compile-time constant // int Local(int j = Local()) => 0; Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "Local()").WithArguments("j").WithLocation(6, 27)); comp.DeclarationDiagnostics.Verify(); } [Fact] [WorkItem(16451, "https://github.com/dotnet/roslyn/issues/16451")] public void RecursiveDefaultParameter2() { var comp = CreateCompilation(@" using System; class C { void M() { int Local(Action a = Local) => 0; Local(); } }"); comp.VerifyDiagnostics( // (7,30): error CS1736: Default parameter value for 'a' must be a compile-time constant // int Local(Action a = Local) => 0; Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "Local").WithArguments("a").WithLocation(7, 30)); comp.DeclarationDiagnostics.Verify(); } [Fact] [WorkItem(16451, "https://github.com/dotnet/roslyn/issues/16451")] public void MutuallyRecursiveDefaultParameters() { var comp = CreateCompilation(@" class C { void M() { int Local1(int p = Local2()) => 0; int Local2(int p = Local1()) => 0; Local1(); Local2(); } }"); comp.VerifyDiagnostics( // (6,28): error CS1736: Default parameter value for 'p' must be a compile-time constant // int Local1(int p = Local2()) => 0; Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "Local2()").WithArguments("p").WithLocation(6, 28), // (7,28): error CS1736: Default parameter value for 'p' must be a compile-time constant // int Local2(int p = Local1()) => 0; Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "Local1()").WithArguments("p").WithLocation(7, 28)); comp.DeclarationDiagnostics.Verify(); } [Fact] public void FetchLocalFunctionSymbolThroughLocal() { var tree = SyntaxFactory.ParseSyntaxTree(@" using System; class C { public void M() { void Local<[A, B, CLSCompliant, D]T>() { var x = new object(); } Local<int>(); } }"); var comp = CreateCompilation(tree); comp.DeclarationDiagnostics.Verify(); comp.VerifyDiagnostics( // (7,21): error CS0246: The type or namespace name 'AAttribute' could not be found (are you missing a using directive or an assembly reference?) // void Local<[A, B, CLSCompliant, D]T>() Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A").WithArguments("AAttribute").WithLocation(7, 21), // (7,21): error CS0246: The type or namespace name 'A' could not be found (are you missing a using directive or an assembly reference?) // void Local<[A, B, CLSCompliant, D]T>() Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A").WithArguments("A").WithLocation(7, 21), // (7,24): error CS0246: The type or namespace name 'BAttribute' could not be found (are you missing a using directive or an assembly reference?) // void Local<[A, B, CLSCompliant, D]T>() Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "B").WithArguments("BAttribute").WithLocation(7, 24), // (7,24): error CS0246: The type or namespace name 'B' could not be found (are you missing a using directive or an assembly reference?) // void Local<[A, B, CLSCompliant, D]T>() Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "B").WithArguments("B").WithLocation(7, 24), // (7,41): error CS0246: The type or namespace name 'DAttribute' could not be found (are you missing a using directive or an assembly reference?) // void Local<[A, B, CLSCompliant, D]T>() Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "D").WithArguments("DAttribute").WithLocation(7, 41), // (7,41): error CS0246: The type or namespace name 'D' could not be found (are you missing a using directive or an assembly reference?) // void Local<[A, B, CLSCompliant, D]T>() Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "D").WithArguments("D").WithLocation(7, 41), // (7,27): error CS7036: There is no argument given that corresponds to the required formal parameter 'isCompliant' of 'CLSCompliantAttribute.CLSCompliantAttribute(bool)' // void Local<[A, B, CLSCompliant, D]T>() Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "CLSCompliant").WithArguments("isCompliant", "System.CLSCompliantAttribute.CLSCompliantAttribute(bool)").WithLocation(7, 27)); var model = comp.GetSemanticModel(tree); var x = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(v => v.Identifier.ValueText == "x").Single(); var localSymbol = model.GetDeclaredSymbol(x).ContainingSymbol.GetSymbol<LocalFunctionSymbol>(); var typeParam = localSymbol.TypeParameters.Single(); var attrs = typeParam.GetAttributes(); Assert.True(attrs[0].AttributeClass.IsErrorType()); Assert.True(attrs[1].AttributeClass.IsErrorType()); Assert.False(attrs[2].AttributeClass.IsErrorType()); Assert.Equal(comp.GlobalNamespace .GetMember<NamespaceSymbol>("System") .GetMember<NamedTypeSymbol>("CLSCompliantAttribute"), attrs[2].AttributeClass); Assert.True(attrs[3].AttributeClass.IsErrorType()); comp.DeclarationDiagnostics.Verify(); } [Fact] public void TypeParameterAttributesInSemanticModel() { var comp = (Compilation)CreateCompilation(@" using System; class C { public void M() { void Local<[A]T, [CLSCompliant]U>() { } } }", parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,21): error CS0246: The type or namespace name 'AAttribute' could not be found (are you missing a using directive or an assembly reference?) // void Local<[A]T, [CLSCompliant]U>() { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A").WithArguments("AAttribute").WithLocation(7, 21), // (7,21): error CS0246: The type or namespace name 'A' could not be found (are you missing a using directive or an assembly reference?) // void Local<[A]T, [CLSCompliant]U>() { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A").WithArguments("A").WithLocation(7, 21), // (7,27): error CS7036: There is no argument given that corresponds to the required formal parameter 'isCompliant' of 'CLSCompliantAttribute.CLSCompliantAttribute(bool)' // void Local<[A]T, [CLSCompliant]U>() { } Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "CLSCompliant").WithArguments("isCompliant", "System.CLSCompliantAttribute.CLSCompliantAttribute(bool)").WithLocation(7, 27), // (7,14): warning CS8321: The local function 'Local' is declared but never used // void Local<[A]T, [CLSCompliant]U>() { } Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local").WithArguments("Local").WithLocation(7, 14)); var tree = comp.SyntaxTrees.First(); var root = tree.GetRoot(); var model = comp.GetSemanticModel(tree); var a = root.DescendantNodes() .OfType<IdentifierNameSyntax>() .Where(id => id.Identifier.ValueText == "A") .Single(); Assert.Null(model.GetDeclaredSymbol(a)); var aSymbolInfo = model.GetSymbolInfo(a); Assert.Equal(0, aSymbolInfo.CandidateSymbols.Length); Assert.Null(aSymbolInfo.Symbol); var aTypeInfo = model.GetTypeInfo(a); Assert.Equal(TypeKind.Error, aTypeInfo.Type.TypeKind); Assert.Null(model.GetAliasInfo(a)); Assert.Empty(model.LookupNamespacesAndTypes(a.SpanStart, name: "A")); var clsCompliant = root.DescendantNodes() .OfType<IdentifierNameSyntax>() .Where(id => id.Identifier.ValueText == "CLSCompliant") .Single(); var clsCompliantSymbol = comp.GlobalNamespace .GetMember<INamespaceSymbol>("System") .GetTypeMember("CLSCompliantAttribute"); Assert.Null(model.GetDeclaredSymbol(clsCompliant)); // This should be null because there is no CLSCompliant ctor with no args var clsCompliantSymbolInfo = model.GetSymbolInfo(clsCompliant); Assert.Null(clsCompliantSymbolInfo.Symbol); Assert.Equal(clsCompliantSymbol.GetMember<IMethodSymbol>(".ctor"), clsCompliantSymbolInfo.CandidateSymbols.Single()); Assert.Equal(CandidateReason.OverloadResolutionFailure, clsCompliantSymbolInfo.CandidateReason); Assert.Equal(clsCompliantSymbol, model.GetTypeInfo(clsCompliant).Type); Assert.Null(model.GetAliasInfo(clsCompliant)); Assert.Equal(clsCompliantSymbol, model.LookupNamespacesAndTypes(clsCompliant.SpanStart, name: "CLSCompliantAttribute").Single()); ((CSharpCompilation)comp).DeclarationDiagnostics.Verify(); } [Fact] public void ParameterAttributesInSemanticModel() { var comp = (Compilation)CreateCompilation(@" using System; class C { public void M() { void Local([A]int x, [CLSCompliant]int y) { } } }", parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,21): error CS0246: The type or namespace name 'AAttribute' could not be found (are you missing a using directive or an assembly reference?) // void Local([A]int x, [CLSCompliant]int y) { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A").WithArguments("AAttribute").WithLocation(7, 21), // (7,21): error CS0246: The type or namespace name 'A' could not be found (are you missing a using directive or an assembly reference?) // void Local([A]int x, [CLSCompliant]int y) { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A").WithArguments("A").WithLocation(7, 21), // (7,31): error CS7036: There is no argument given that corresponds to the required formal parameter 'isCompliant' of 'CLSCompliantAttribute.CLSCompliantAttribute(bool)' // void Local([A]int x, [CLSCompliant]int y) { } Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "CLSCompliant").WithArguments("isCompliant", "System.CLSCompliantAttribute.CLSCompliantAttribute(bool)").WithLocation(7, 31), // (7,14): warning CS8321: The local function 'Local' is declared but never used // void Local([A]int x, [CLSCompliant]int y) { } Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local").WithArguments("Local").WithLocation(7, 14)); var tree = comp.SyntaxTrees.First(); var root = tree.GetRoot(); var model = comp.GetSemanticModel(tree); var a = root.DescendantNodes() .OfType<IdentifierNameSyntax>() .Where(id => id.Identifier.ValueText == "A") .Single(); Assert.Null(model.GetDeclaredSymbol(a)); var aSymbolInfo = model.GetSymbolInfo(a); Assert.Equal(0, aSymbolInfo.CandidateSymbols.Length); Assert.Null(aSymbolInfo.Symbol); var aTypeInfo = model.GetTypeInfo(a); Assert.Equal(TypeKind.Error, aTypeInfo.Type.TypeKind); Assert.Null(model.GetAliasInfo(a)); Assert.Empty(model.LookupNamespacesAndTypes(a.SpanStart, name: "A")); var clsCompliant = root.DescendantNodes() .OfType<IdentifierNameSyntax>() .Where(id => id.Identifier.ValueText == "CLSCompliant") .Single(); var clsCompliantSymbol = comp.GlobalNamespace .GetMember<INamespaceSymbol>("System") .GetTypeMember("CLSCompliantAttribute"); Assert.Null(model.GetDeclaredSymbol(clsCompliant)); // This should be null because there is no CLSCompliant ctor with no args var clsCompliantSymbolInfo = model.GetSymbolInfo(clsCompliant); Assert.Null(clsCompliantSymbolInfo.Symbol); Assert.Equal(clsCompliantSymbol.GetMember<IMethodSymbol>(".ctor"), clsCompliantSymbolInfo.CandidateSymbols.Single()); Assert.Equal(CandidateReason.OverloadResolutionFailure, clsCompliantSymbolInfo.CandidateReason); Assert.Equal(clsCompliantSymbol, model.GetTypeInfo(clsCompliant).Type); Assert.Null(model.GetAliasInfo(clsCompliant)); Assert.Equal(clsCompliantSymbol, model.LookupNamespacesAndTypes(clsCompliant.SpanStart, name: "CLSCompliantAttribute").Single()); ((CSharpCompilation)comp).DeclarationDiagnostics.Verify(); } [Fact] public void LocalFunctionAttribute_TypeParameter_Errors() { var tree = SyntaxFactory.ParseSyntaxTree(@" using System; class C { public void M() { void Local<[A, B, CLSCompliant, D]T>() { } Local<int>(); } }", options: TestOptions.Regular9); var comp = CreateCompilation(tree); comp.DeclarationDiagnostics.Verify(); comp.VerifyDiagnostics( // (7,21): error CS0246: The type or namespace name 'AAttribute' could not be found (are you missing a using directive or an assembly reference?) // void Local<[A, B, CLSCompliant, D]T>() { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A").WithArguments("AAttribute").WithLocation(7, 21), // (7,21): error CS0246: The type or namespace name 'A' could not be found (are you missing a using directive or an assembly reference?) // void Local<[A, B, CLSCompliant, D]T>() { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A").WithArguments("A").WithLocation(7, 21), // (7,24): error CS0246: The type or namespace name 'BAttribute' could not be found (are you missing a using directive or an assembly reference?) // void Local<[A, B, CLSCompliant, D]T>() { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "B").WithArguments("BAttribute").WithLocation(7, 24), // (7,24): error CS0246: The type or namespace name 'B' could not be found (are you missing a using directive or an assembly reference?) // void Local<[A, B, CLSCompliant, D]T>() { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "B").WithArguments("B").WithLocation(7, 24), // (7,41): error CS0246: The type or namespace name 'DAttribute' could not be found (are you missing a using directive or an assembly reference?) // void Local<[A, B, CLSCompliant, D]T>() { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "D").WithArguments("DAttribute").WithLocation(7, 41), // (7,41): error CS0246: The type or namespace name 'D' could not be found (are you missing a using directive or an assembly reference?) // void Local<[A, B, CLSCompliant, D]T>() { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "D").WithArguments("D").WithLocation(7, 41), // (7,27): error CS7036: There is no argument given that corresponds to the required formal parameter 'isCompliant' of 'CLSCompliantAttribute.CLSCompliantAttribute(bool)' // void Local<[A, B, CLSCompliant, D]T>() { } Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "CLSCompliant").WithArguments("isCompliant", "System.CLSCompliantAttribute.CLSCompliantAttribute(bool)").WithLocation(7, 27)); var localDecl = tree.FindNodeOrTokenByKind(SyntaxKind.LocalFunctionStatement); var model = comp.GetSemanticModel(tree); var localSymbol = Assert.IsType<LocalFunctionSymbol>(model.GetDeclaredSymbol(localDecl.AsNode()).GetSymbol()); var typeParam = localSymbol.TypeParameters.Single(); var attrs = typeParam.GetAttributes(); Assert.True(attrs[0].AttributeClass.IsErrorType()); Assert.True(attrs[1].AttributeClass.IsErrorType()); Assert.False(attrs[2].AttributeClass.IsErrorType()); Assert.Equal(comp.GlobalNamespace .GetMember<NamespaceSymbol>("System") .GetMember<NamedTypeSymbol>("CLSCompliantAttribute"), attrs[2].AttributeClass); Assert.True(attrs[3].AttributeClass.IsErrorType()); comp.DeclarationDiagnostics.Verify(); } [Fact] public void LocalFunctionAttribute_Parameter_Errors() { var tree = SyntaxFactory.ParseSyntaxTree(@" using System; class C { public void M() { void Local([A, B]int x, [CLSCompliant]string s = """") { } Local(0); } }", options: TestOptions.Regular9); var comp = CreateCompilation(tree); comp.DeclarationDiagnostics.Verify(); comp.VerifyDiagnostics( // (7,21): error CS0246: The type or namespace name 'AAttribute' could not be found (are you missing a using directive or an assembly reference?) // void Local([A, B]int x, [CLSCompliant]string s = "") { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A").WithArguments("AAttribute").WithLocation(7, 21), // (7,21): error CS0246: The type or namespace name 'A' could not be found (are you missing a using directive or an assembly reference?) // void Local([A, B]int x, [CLSCompliant]string s = "") { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A").WithArguments("A").WithLocation(7, 21), // (7,24): error CS0246: The type or namespace name 'BAttribute' could not be found (are you missing a using directive or an assembly reference?) // void Local([A, B]int x, [CLSCompliant]string s = "") { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "B").WithArguments("BAttribute").WithLocation(7, 24), // (7,24): error CS0246: The type or namespace name 'B' could not be found (are you missing a using directive or an assembly reference?) // void Local([A, B]int x, [CLSCompliant]string s = "") { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "B").WithArguments("B").WithLocation(7, 24), // (7,34): error CS7036: There is no argument given that corresponds to the required formal parameter 'isCompliant' of 'CLSCompliantAttribute.CLSCompliantAttribute(bool)' // void Local([A, B]int x, [CLSCompliant]string s = "") { } Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "CLSCompliant").WithArguments("isCompliant", "System.CLSCompliantAttribute.CLSCompliantAttribute(bool)").WithLocation(7, 34)); var localDecl = tree.FindNodeOrTokenByKind(SyntaxKind.LocalFunctionStatement); var model = comp.GetSemanticModel(tree); var localSymbol = Assert.IsType<LocalFunctionSymbol>(model.GetDeclaredSymbol(localDecl.AsNode()).GetSymbol()); var param = localSymbol.Parameters[0]; var attrs = param.GetAttributes(); Assert.True(attrs[0].AttributeClass.IsErrorType()); Assert.True(attrs[1].AttributeClass.IsErrorType()); param = localSymbol.Parameters[1]; attrs = param.GetAttributes(); Assert.Equal(comp.GlobalNamespace .GetMember<NamespaceSymbol>("System") .GetMember<NamedTypeSymbol>("CLSCompliantAttribute"), attrs[0].AttributeClass); comp.DeclarationDiagnostics.Verify(); } [Fact] public void LocalFunctionDisallowedAttributes() { var source = @" using System.Runtime.CompilerServices; namespace System.Runtime.CompilerServices { public class IsReadOnlyAttribute : System.Attribute { } public class IsUnmanagedAttribute : System.Attribute { } public class IsByRefLikeAttribute : System.Attribute { } public class NullableContextAttribute : System.Attribute { public NullableContextAttribute(byte b) { } } } class C { void M() { local1(); [IsReadOnly] // 1 [IsUnmanaged] // 2 [IsByRefLike] // 3 [Extension] // 4 [NullableContext(0)] // 5 void local1() { } } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (18,10): error CS8335: Do not use 'System.Runtime.CompilerServices.IsReadOnlyAttribute'. This is reserved for compiler usage. // [IsReadOnly] // 1 Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsReadOnly").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute").WithLocation(18, 10), // (19,10): error CS8335: Do not use 'System.Runtime.CompilerServices.IsUnmanagedAttribute'. This is reserved for compiler usage. // [IsUnmanaged] // 2 Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsUnmanaged").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute").WithLocation(19, 10), // (20,10): error CS8335: Do not use 'System.Runtime.CompilerServices.IsByRefLikeAttribute'. This is reserved for compiler usage. // [IsByRefLike] // 3 Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsByRefLike").WithArguments("System.Runtime.CompilerServices.IsByRefLikeAttribute").WithLocation(20, 10), // (21,10): error CS1112: Do not use 'System.Runtime.CompilerServices.ExtensionAttribute'. Use the 'this' keyword instead. // [Extension] // 4 Diagnostic(ErrorCode.ERR_ExplicitExtension, "Extension").WithLocation(21, 10), // (22,10): error CS8335: Do not use 'System.Runtime.CompilerServices.NullableContextAttribute'. This is reserved for compiler usage. // [NullableContext(0)] // 5 Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "NullableContext(0)").WithArguments("System.Runtime.CompilerServices.NullableContextAttribute").WithLocation(22, 10)); } [Fact] public void LocalFunctionDisallowedSecurityAttributes() { var source = @" using System.Security; class C { void M() { local1(); [SecurityCritical] // 1 [SecuritySafeCriticalAttribute] // 2 async void local1() // 3 { } } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (10,10): error CS4030: Security attribute 'SecurityCritical' cannot be applied to an Async method. // [SecurityCritical] // 1 Diagnostic(ErrorCode.ERR_SecurityCriticalOrSecuritySafeCriticalOnAsync, "SecurityCritical").WithArguments("SecurityCritical").WithLocation(10, 10), // (11,10): error CS4030: Security attribute 'SecuritySafeCriticalAttribute' cannot be applied to an Async method. // [SecuritySafeCriticalAttribute] // 2 Diagnostic(ErrorCode.ERR_SecurityCriticalOrSecuritySafeCriticalOnAsync, "SecuritySafeCriticalAttribute").WithArguments("SecuritySafeCriticalAttribute").WithLocation(11, 10), // (12,20): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread. // async void local1() // 3 Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "local1").WithLocation(12, 20)); } [Fact] public void TypeParameterBindingScope() { var src = @" class C { public void M() { { int T = 0; // Should not have error int Local<T>() => 0; // Should conflict with above Local<int>(); T++; } { int T<T>() => 0; T<int>(); } { int Local<T, T>() => 0; Local<int, int>(); } } public void M2<T>() { { int Local<T>() => 0; Local<int>(); } { int Local1<V>() { int Local2<V>() => 0; return Local2<int>(); } Local1<int>(); } { int T() => 0; T(); } { int Local1<V>() { int V() => 0; return V(); } Local1<int>(); } { int Local1<V>() { int Local2<U>() { // Conflicts with method type parameter int T() => 0; return T(); } return Local2<int>(); } Local1<int>(); } { int Local1<V>() { int Local2<U>() { // Shadows M.2<T> int Local3<T>() => 0; return Local3<int>(); } return Local2<int>(); } Local1<int>(); } } public void V<V>() { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics( // (9,23): error CS0136: A local or parameter named 'T' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int Local<T>() => 0; // Should conflict with above Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "T").WithArguments("T").WithLocation(9, 23), // (14,19): error CS0136: A local or parameter named 'T' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int T<T>() => 0; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "T").WithArguments("T").WithLocation(14, 19), // (18,26): error CS0692: Duplicate type parameter 'T' // int Local<T, T>() => 0; Diagnostic(ErrorCode.ERR_DuplicateTypeParameter, "T").WithArguments("T").WithLocation(18, 26), // (25,23): warning CS8387: Type parameter 'T' has the same name as the type parameter from outer method 'C.M2<T>()' // int Local<T>() => 0; Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterMethodTypeParameter, "T").WithArguments("T", "C.M2<T>()").WithLocation(25, 23), // (31,28): warning CS8387: Type parameter 'V' has the same name as the type parameter from outer method 'Local1<V>()' // int Local2<V>() => 0; Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterMethodTypeParameter, "V").WithArguments("V", "Local1<V>()").WithLocation(31, 28), // (37,17): error CS0412: 'T': a parameter, local variable, or local function cannot have the same name as a method type parameter // int T() => 0; Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "T").WithArguments("T").WithLocation(37, 17), // (43,21): error CS0412: 'V': a parameter, local variable, or local function cannot have the same name as a method type parameter // int V() => 0; Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "V").WithArguments("V").WithLocation(43, 21), // (54,25): error CS0412: 'T': a parameter, local variable, or local function cannot have the same name as a method type parameter // int T() => 0; Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "T").WithArguments("T").WithLocation(54, 25), // (67,32): warning CS8387: Type parameter 'T' has the same name as the type parameter from outer method 'C.M2<T>()' // int Local3<T>() => 0; Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterMethodTypeParameter, "T").WithArguments("T", "C.M2<T>()").WithLocation(67, 32)); comp = CreateCompilation(src, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (18,26): error CS0692: Duplicate type parameter 'T' // int Local<T, T>() => 0; Diagnostic(ErrorCode.ERR_DuplicateTypeParameter, "T").WithArguments("T").WithLocation(18, 26), // (25,23): warning CS8387: Type parameter 'T' has the same name as the type parameter from outer method 'C.M2<T>()' // int Local<T>() => 0; Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterMethodTypeParameter, "T").WithArguments("T", "C.M2<T>()").WithLocation(25, 23), // (31,28): warning CS8387: Type parameter 'V' has the same name as the type parameter from outer method 'Local1<V>()' // int Local2<V>() => 0; Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterMethodTypeParameter, "V").WithArguments("V", "Local1<V>()").WithLocation(31, 28), // (37,17): error CS0412: 'T': a parameter, local variable, or local function cannot have the same name as a method type parameter // int T() => 0; Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "T").WithArguments("T").WithLocation(37, 17), // (43,21): error CS0412: 'V': a parameter, local variable, or local function cannot have the same name as a method type parameter // int V() => 0; Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "V").WithArguments("V").WithLocation(43, 21), // (67,32): warning CS8387: Type parameter 'T' has the same name as the type parameter from outer method 'C.M2<T>()' // int Local3<T>() => 0; Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterMethodTypeParameter, "T").WithArguments("T", "C.M2<T>()").WithLocation(67, 32)); } [Fact] public void LocalFuncAndTypeParameterOnType() { var comp = CreateCompilation(@" class C2<T> { public void M() { { int Local1() { int Local2<T>() => 0; return Local2<int>(); } Local1(); } { int Local1() { int Local2() { // Shadows type parameter int T() => 0; // Type parameter resolves in type only context T t = default(T); // Ambiguous context chooses local T.M(); // Call chooses local return T(); } return Local2(); } Local1(); } } }"); comp.VerifyDiagnostics( // (9,28): warning CS0693: Type parameter 'T' has the same name as the type parameter from outer type 'C2<T>' // int Local2<T>() => 0; Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, "T").WithArguments("T", "C2<T>").WithLocation(9, 28), // (26,21): error CS0119: 'T()' is a method, which is not valid in the given context // T.M(); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T()", "method").WithLocation(26, 21), // (23,23): warning CS0219: The variable 't' is assigned but its value is never used // T t = default(T); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "t").WithArguments("t").WithLocation(23, 23)); } [Fact] public void RefArgsInIteratorLocalFuncs() { var src = @" using System; using System.Collections.Generic; class C { public void M1() { IEnumerable<int> Local(ref int a) { yield break; } int x = 0; Local(ref x); } public void M2() { Action a = () => { IEnumerable<int> Local(ref int x) { yield break; } int y = 0; Local(ref y); return; }; a(); } public Func<int> M3() => (() => { IEnumerable<int> Local(ref int a) { yield break; } int x = 0; Local(ref x); return 0; }); public IEnumerable<int> M4(ref int a) { yield return new Func<int>(() => { IEnumerable<int> Local(ref int b) { yield break; } int x = 0; Local(ref x); return 0; })(); } }"; VerifyDiagnostics(src, // (8,40): error CS1623: Iterators cannot have ref, in or out parameters // IEnumerable<int> Local(ref int a) { yield break; } Diagnostic(ErrorCode.ERR_BadIteratorArgType, "a").WithLocation(8, 40), // (17,44): error CS1623: Iterators cannot have ref, in or out parameters // IEnumerable<int> Local(ref int x) { yield break; } Diagnostic(ErrorCode.ERR_BadIteratorArgType, "x").WithLocation(17, 44), // (27,40): error CS1623: Iterators cannot have ref, in or out parameters // IEnumerable<int> Local(ref int a) { yield break; } Diagnostic(ErrorCode.ERR_BadIteratorArgType, "a").WithLocation(27, 40), // (33,40): error CS1623: Iterators cannot have ref, in or out parameters // public IEnumerable<int> M4(ref int a) Diagnostic(ErrorCode.ERR_BadIteratorArgType, "a").WithLocation(33, 40), // (37,48): error CS1623: Iterators cannot have ref, in or out parameters // IEnumerable<int> Local(ref int b) { yield break; } Diagnostic(ErrorCode.ERR_BadIteratorArgType, "b").WithLocation(37, 48)); } [Fact] public void UnsafeArgsInIteratorLocalFuncs() { var src = @" using System; using System.Collections.Generic; class C { public unsafe void M1() { IEnumerable<int> Local(int* a) { yield break; } int x = 0; Local(&x); } public unsafe void M2() { Action a = () => { IEnumerable<int> Local(int* x) { yield break; } int y = 0; Local(&y); return; }; a(); } public unsafe Func<int> M3() => (() => { IEnumerable<int> Local(int* a) { yield break; } int x = 0; Local(&x); return 0; }); public unsafe IEnumerable<int> M4(int* a) { yield return new Func<int>(() => { IEnumerable<int> Local(int* b) { yield break; } int x = 0; Local(&x); return 0; })(); } }"; CreateCompilation(src, options: TestOptions.UnsafeDebugDll) .VerifyDiagnostics( // (8,37): error CS1637: Iterators cannot have unsafe parameters or yield types // IEnumerable<int> Local(int* a) { yield break; } Diagnostic(ErrorCode.ERR_UnsafeIteratorArgType, "a").WithLocation(8, 37), // (17,41): error CS1637: Iterators cannot have unsafe parameters or yield types // IEnumerable<int> Local(int* x) { yield break; } Diagnostic(ErrorCode.ERR_UnsafeIteratorArgType, "x").WithLocation(17, 41), // (27,37): error CS1637: Iterators cannot have unsafe parameters or yield types // IEnumerable<int> Local(int* a) { yield break; } Diagnostic(ErrorCode.ERR_UnsafeIteratorArgType, "a").WithLocation(27, 37), // (33,44): error CS1637: Iterators cannot have unsafe parameters or yield types // public unsafe IEnumerable<int> M4(int* a) Diagnostic(ErrorCode.ERR_UnsafeIteratorArgType, "a").WithLocation(33, 44), // (33,36): error CS1629: Unsafe code may not appear in iterators // public unsafe IEnumerable<int> M4(int* a) Diagnostic(ErrorCode.ERR_IllegalInnerUnsafe, "M4").WithLocation(33, 36), // (37,40): error CS1629: Unsafe code may not appear in iterators // IEnumerable<int> Local(int* b) { yield break; } Diagnostic(ErrorCode.ERR_IllegalInnerUnsafe, "int*").WithLocation(37, 40), // (39,23): error CS1629: Unsafe code may not appear in iterators // Local(&x); Diagnostic(ErrorCode.ERR_IllegalInnerUnsafe, "&x").WithLocation(39, 23), // (39,17): error CS1629: Unsafe code may not appear in iterators // Local(&x); Diagnostic(ErrorCode.ERR_IllegalInnerUnsafe, "Local(&x)").WithLocation(39, 17), // (37,45): error CS1637: Iterators cannot have unsafe parameters or yield types // IEnumerable<int> Local(int* b) { yield break; } Diagnostic(ErrorCode.ERR_UnsafeIteratorArgType, "b").WithLocation(37, 45)); } [Fact] [WorkItem(13193, "https://github.com/dotnet/roslyn/issues/13193")] public void LocalFunctionConflictingName() { var comp = CreateCompilation(@" class C { public void M<TLocal>() { void TLocal() { } TLocal(); } public void M(int Local) { void Local() { } Local(); } public void M() { int local = 0; void local() { } local(); } }"); comp.VerifyDiagnostics( // (6,14): error CS0412: 'TLocal': a parameter, local variable, or local function cannot have the same name as a method type parameter // void TLocal() { } Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "TLocal").WithArguments("TLocal").WithLocation(6, 14), // (11,14): error CS0136: A local or parameter named 'Local' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // void Local() { } Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "Local").WithArguments("Local").WithLocation(11, 14), // (18,14): error CS0128: A local variable or function named 'local' is already defined in this scope // void local() { } Diagnostic(ErrorCode.ERR_LocalDuplicate, "local").WithArguments("local").WithLocation(18, 14), // (16,13): warning CS0219: The variable 'local' is assigned but its value is never used // int local = 0; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "local").WithArguments("local").WithLocation(16, 13)); } [Fact] public void ForgotSemicolonLocalFunctionsMistake() { var src = @" class C { public void M1() { // forget closing brace public void BadLocal1() { this.BadLocal2(); } public void BadLocal2() { } public int P => 0; }"; VerifyDiagnostics(src, // (8,5): error CS0106: The modifier 'public' is not valid for this item // public void BadLocal1() Diagnostic(ErrorCode.ERR_BadMemberFlag, "public").WithArguments("public").WithLocation(8, 5), // (13,5): error CS0106: The modifier 'public' is not valid for this item // public void BadLocal2() Diagnostic(ErrorCode.ERR_BadMemberFlag, "public").WithArguments("public").WithLocation(13, 5), // (15,6): error CS1513: } expected // } Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(15, 6), // (10,14): error CS1061: 'C' does not contain a definition for 'BadLocal2' and no extension method 'BadLocal2' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?) // this.BadLocal2(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "BadLocal2").WithArguments("C", "BadLocal2").WithLocation(10, 14), // (8,17): warning CS8321: The local function 'BadLocal1' is declared but never used // public void BadLocal1() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "BadLocal1").WithArguments("BadLocal1").WithLocation(8, 17), // (13,17): warning CS8321: The local function 'BadLocal2' is declared but never used // public void BadLocal2() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "BadLocal2").WithArguments("BadLocal2").WithLocation(13, 17)); } [Fact] public void VarLocalFunction() { var src = @" class C { void M() { var local() => 0; int x = local(); } }"; VerifyDiagnostics(src, // (6,9): error CS0825: The contextual keyword 'var' may only appear within a local variable declaration or in script code // var local() => 0; Diagnostic(ErrorCode.ERR_TypeVarNotFound, "var").WithLocation(6, 9)); } [Fact] public void VarLocalFunction2() { var comp = CreateCompilation(@" class C { private class var { } void M() { var local() => new var(); var x = local(); } }", parseOptions: DefaultParseOptions); comp.VerifyDiagnostics(); } [Fact] [CompilerTrait(CompilerFeature.Params)] public void BadParams() { var source = @" using System; class Program { static void Main(string[] args) { void Params(params int x) { Console.WriteLine(x); } Params(2); } } "; VerifyDiagnostics(source, // (8,21): error CS0225: The params parameter must be a single dimensional array // void Params(params int x) Diagnostic(ErrorCode.ERR_ParamsMustBeArray, "params").WithLocation(8, 21) ); } [Fact] public void BadRefWithDefault() { var source = @" class Program { static void Main(string[] args) { void RefOut(ref int x = 2) { x++; } int y = 2; RefOut(ref y); } } "; VerifyDiagnostics(source, // (6,21): error CS1741: A ref or out parameter cannot have a default value // void RefOut(ref int x = 2) Diagnostic(ErrorCode.ERR_RefOutDefaultValue, "ref").WithLocation(6, 21) ); } [Fact] public void BadDefaultValueType() { var source = @" using System; class Program { static void Main(string[] args) { void NamedOptional(string x = 2) { Console.WriteLine(x); } NamedOptional(""2""); } } "; VerifyDiagnostics(source, // (8,35): error CS1750: A value of type 'int' cannot be used as a default parameter because there are no standard conversions to type 'string' // void NamedOptional(string x = 2) Diagnostic(ErrorCode.ERR_NoConversionForDefaultParam, "x").WithArguments("int", "string").WithLocation(8, 35) ); } [Fact] public void CallerMemberName() { var comp = CreateCompilationWithMscorlib46(@" using System; using System.Runtime.CompilerServices; class C { static void Main() { void CallerMemberName([CallerMemberName] string s = null) { Console.Write(s); } void LocalFuncName() { CallerMemberName(); } LocalFuncName(); Console.Write(' '); CallerMemberName(); } }", parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); } [Fact] public void BadCallerMemberName() { var source = @" using System; using System.Runtime.CompilerServices; class Program { static void Main(string[] args) { void CallerMemberName([CallerMemberName] int s = 2) // 1 { Console.WriteLine(s); } CallerMemberName(); // 2 } } "; CreateCompilationWithMscorlib45AndCSharp(source, parseOptions: TestOptions.Regular9).VerifyDiagnostics( // (9,32): error CS4019: CallerMemberNameAttribute cannot be applied because there are no standard conversions from type 'string' to type 'int' // void CallerMemberName([CallerMemberName] int s = 2) // 1 Diagnostic(ErrorCode.ERR_NoConversionForCallerMemberNameParam, "CallerMemberName").WithArguments("string", "int").WithLocation(9, 32), // (13,9): error CS0029: Cannot implicitly convert type 'string' to 'int' // CallerMemberName(); // 2 Diagnostic(ErrorCode.ERR_NoImplicitConv, "CallerMemberName()").WithArguments("string", "int").WithLocation(13, 9)); } [WorkItem(10708, "https://github.com/dotnet/roslyn/issues/10708")] [CompilerTrait(CompilerFeature.Dynamic, CompilerFeature.Params)] [Fact] public void DynamicArgumentToParams() { var src = @" using System; class C { static void Main() { void L1(int x = 0, params int[] ys) => Console.Write(x); dynamic val = 2; L1(val, val); L1(ys: val, x: val); L1(ys: val); } }"; VerifyDiagnostics(src, // (10,9): error CS8106: Cannot pass argument with dynamic type to params parameter 'ys' of local function 'L1'. // L1(val, val); Diagnostic(ErrorCode.ERR_DynamicLocalFunctionParamsParameter, "L1(val, val)").WithArguments("ys", "L1").WithLocation(10, 9), // (11,9): error CS8106: Cannot pass argument with dynamic type to params parameter 'ys' of local function 'L1'. // L1(ys: val, x: val); Diagnostic(ErrorCode.ERR_DynamicLocalFunctionParamsParameter, "L1(ys: val, x: val)").WithArguments("ys", "L1").WithLocation(11, 9), // (12,9): error CS8106: Cannot pass argument with dynamic type to params parameter 'ys' of local function 'L1'. // L1(ys: val); Diagnostic(ErrorCode.ERR_DynamicLocalFunctionParamsParameter, "L1(ys: val)").WithArguments("ys", "L1").WithLocation(12, 9)); } [Fact] [CompilerTrait(CompilerFeature.Dynamic)] public void DynamicArgOverload() { var src = @" using System; class C { static void Main() { void Overload(int i) => Console.Write(i); void Overload(string s) => Console.Write(s); dynamic val = 2; Overload(val); } }"; VerifyDiagnostics(src, // (8,14): error CS0128: A local variable named 'Overload' is already defined in this scope // void Overload(string s) => Console.Write(s); Diagnostic(ErrorCode.ERR_LocalDuplicate, "Overload").WithArguments("Overload").WithLocation(8, 14), // (8,14): warning CS8321: The local function 'Overload' is declared but never used // void Overload(string s) => Console.Write(s); Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Overload").WithArguments("Overload").WithLocation(8, 14)); } [Fact] [CompilerTrait(CompilerFeature.Dynamic)] public void DynamicArgWrongArity() { var src = @" using System; class C { static void Main() { void Local(int i) => Console.Write(i); dynamic val = 2; Local(val, val); } }"; VerifyDiagnostics(src, // (10,9): error CS1501: No overload for method 'Local' takes 2 arguments // Local(val, val); Diagnostic(ErrorCode.ERR_BadArgCount, "Local").WithArguments("Local", "2").WithLocation(10, 9)); } [WorkItem(3923, "https://github.com/dotnet/roslyn/issues/3923")] [Fact] public void ExpressionTreeLocalFunctionUsage_01() { var source = @" using System; using System.Linq.Expressions; class Program { static void Main() { T Id<T>(T x) { return x; } Expression<Func<T>> Local<T>(Expression<Func<T>> f) { return f; } Console.Write(Local(() => Id(2))); Console.Write(Local<Func<int, int>>(() => Id)); Console.Write(Local(() => new Func<int, int>(Id))); Console.Write(Local(() => nameof(Id))); } } "; VerifyDiagnostics(source, // (16,35): error CS8096: An expression tree may not contain a reference to a local function // Console.Write(Local(() => Id(2))); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsLocalFunction, "Id(2)").WithLocation(16, 35), // (17,51): error CS8096: An expression tree may not contain a reference to a local function // Console.Write(Local<Func<int, int>>(() => Id)); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsLocalFunction, "Id").WithLocation(17, 51), // (18,35): error CS8096: An expression tree may not contain a reference to a local function // Console.Write(Local(() => new Func<int, int>(Id))); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsLocalFunction, "Id").WithLocation(18, 54) ); } [Fact] public void ExpressionTreeLocalFunctionUsage_02() { var source = @" using System; using System.Linq.Expressions; class Program { static void Main() { static T Id<T>(T x) { return x; } static Expression<Func<T>> Local<T>(Expression<Func<T>> f) { return f; } Console.Write(Local(() => Id(2))); Console.Write(Local<Func<int, int>>(() => Id)); Console.Write(Local(() => new Func<int, int>(Id))); Console.Write(Local(() => nameof(Id))); } } "; VerifyDiagnostics(source, // (16,35): error CS8096: An expression tree may not contain a reference to a local function // Console.Write(Local(() => Id(2))); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsLocalFunction, "Id(2)").WithLocation(16, 35), // (17,51): error CS8096: An expression tree may not contain a reference to a local function // Console.Write(Local<Func<int, int>>(() => Id)); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsLocalFunction, "Id").WithLocation(17, 51), // (18,35): error CS8096: An expression tree may not contain a reference to a local function // Console.Write(Local(() => new Func<int, int>(Id))); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsLocalFunction, "Id").WithLocation(18, 54) ); } [Fact] public void ExpressionTreeLocalFunctionInside() { var source = @" using System; using System.Linq.Expressions; class Program { static void Main() { Expression<Func<int, int>> f = x => { int Local(int y) => y; return Local(x); }; Console.Write(f); } } "; VerifyDiagnostics(source, // (8,40): error CS0834: A lambda expression with a statement body cannot be converted to an expression tree // Expression<Func<int, int>> f = x => Diagnostic(ErrorCode.ERR_StatementLambdaToExpressionTree, @"x => { int Local(int y) => y; return Local(x); }").WithLocation(8, 40), // (11,20): error CS8096: An expression tree may not contain a local function or a reference to a local function // return Local(x); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsLocalFunction, "Local(x)").WithLocation(11, 20) ); } [Fact] public void BadScoping() { var source = @" using System; class Program { static void Main(string[] args) { if (true) { void Local() { Console.WriteLine(2); } Local(); } Local(); Local2(); void Local2() { Console.WriteLine(2); } } } "; VerifyDiagnostics(source, // (16,9): error CS0103: The name 'Local' does not exist in the current context // Local(); Diagnostic(ErrorCode.ERR_NameNotInContext, "Local").WithArguments("Local").WithLocation(16, 9) ); } [Fact] public void NameConflictDuplicate() { var source = @" class Program { static void Main(string[] args) { void Duplicate() { } void Duplicate() { } Duplicate(); } } "; VerifyDiagnostics(source, // (7,14): error CS0128: A local variable named 'Duplicate' is already defined in this scope // void Duplicate() { } Diagnostic(ErrorCode.ERR_LocalDuplicate, "Duplicate").WithArguments("Duplicate").WithLocation(7, 14), // (7,14): warning CS8321: The local function 'Duplicate' is declared but never used // void Duplicate() { } Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Duplicate").WithArguments("Duplicate").WithLocation(7, 14) ); } [Fact] public void NameConflictParameter() { var source = @" class Program { static void Main(string[] args) { int x = 2; void Param(int x) { } Param(x); } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics( // (7,24): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // void Param(int x) { } Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(7, 24)); comp = CreateCompilation(source, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); } [Fact] public void NameConflictTypeParameter() { var source = @" class Program { static void Main(string[] args) { int T; void Generic<T>() { } Generic<int>(); } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics( // (7,22): error CS0136: A local or parameter named 'T' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // void Generic<T>() { } Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "T").WithArguments("T").WithLocation(7, 22), // (6,13): warning CS0168: The variable 'T' is declared but never used // int T; Diagnostic(ErrorCode.WRN_UnreferencedVar, "T").WithArguments("T").WithLocation(6, 13)); comp = CreateCompilation(source, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (6,13): warning CS0168: The variable 'T' is declared but never used // int T; Diagnostic(ErrorCode.WRN_UnreferencedVar, "T").WithArguments("T").WithLocation(6, 13)); } [Fact] public void NameConflictNestedTypeParameter() { var source = @" class Program { static void Main(string[] args) { T Outer<T>() { T Inner<T>() { return default(T); } return Inner<T>(); } System.Console.Write(Outer<int>()); } } "; VerifyDiagnostics(source, // (8,21): warning CS8387: Type parameter 'T' has the same name as the type parameter from outer method 'Outer<T>()' // T Inner<T>() Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterMethodTypeParameter, "T").WithArguments("T", "Outer<T>()").WithLocation(8, 21) ); } [Fact] public void NameConflictLocalVarFirst() { var source = @" class Program { static void Main(string[] args) { int Conflict; void Conflict() { } } } "; VerifyDiagnostics(source, // (7,14): error CS0128: A local variable named 'Conflict' is already defined in this scope // void Conflict() { } Diagnostic(ErrorCode.ERR_LocalDuplicate, "Conflict").WithArguments("Conflict").WithLocation(7, 14), // (6,13): warning CS0168: The variable 'Conflict' is declared but never used // int Conflict; Diagnostic(ErrorCode.WRN_UnreferencedVar, "Conflict").WithArguments("Conflict").WithLocation(6, 13), // (7,14): warning CS8321: The local function 'Conflict' is declared but never used // void Conflict() { } Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Conflict").WithArguments("Conflict").WithLocation(7, 14) ); } [Fact] public void NameConflictLocalVarLast() { var source = @" class Program { static void Main(string[] args) { void Conflict() { } int Conflict; } } "; // TODO: This is strange. Probably has to do with the fact that local variables are preferred over functions. VerifyDiagnostics(source, // (6,14): error CS0136: A local or parameter named 'Conflict' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // void Conflict() { } Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "Conflict").WithArguments("Conflict").WithLocation(6, 14), // (7,13): warning CS0168: The variable 'Conflict' is declared but never used // int Conflict; Diagnostic(ErrorCode.WRN_UnreferencedVar, "Conflict").WithArguments("Conflict").WithLocation(7, 13), // (6,14): warning CS8321: The local function 'Conflict' is declared but never used // void Conflict() { } Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Conflict").WithArguments("Conflict").WithLocation(6, 14) ); } [Fact] public void BadUnsafeNoKeyword() { var source = @" using System; class Program { static void A() { void Local() { int x = 2; Console.WriteLine(*&x); } Local(); } static void Main(string[] args) { A(); } } "; VerifyDiagnostics(source, // (11,32): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // Console.WriteLine(*&x); Diagnostic(ErrorCode.ERR_UnsafeNeeded, "&x").WithLocation(11, 32) ); } [Fact] public void BadUnsafeKeywordDoesntApply() { var source = @" using System; class Program { static unsafe void B() { void Local() { int x = 2; Console.WriteLine(*&x); } Local(); } static void Main(string[] args) { B(); } } "; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe.WithAllowUnsafe(true)); comp.VerifyDiagnostics(); } [Fact] public void BadEmptyBody() { var source = @" class Program { static void Main(string[] args) { void Local(int x); Local(2); } }"; VerifyDiagnostics(source, // (6,14): error CS8112: 'Local(int)' is a local function and must therefore always have a body. // void Local(int x); Diagnostic(ErrorCode.ERR_LocalFunctionMissingBody, "Local").WithArguments("Local(int)").WithLocation(6, 14) ); } [Fact] public void BadGotoInto() { var source = @" using System; class Program { static void Main(string[] args) { goto A; void Local() { A: Console.Write(2); } Local(); } }"; VerifyDiagnostics(source, // (8,14): error CS0159: No such label 'A' within the scope of the goto statement // goto A; Diagnostic(ErrorCode.ERR_LabelNotFound, "A").WithArguments("A").WithLocation(8, 14), // (11,9): warning CS0164: This label has not been referenced // A: Console.Write(2); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "A").WithLocation(11, 9) ); } [Fact] public void BadGotoOutOf() { var source = @" class Program { static void Main(string[] args) { void Local() { goto A; } A: Local(); } }"; VerifyDiagnostics(source, // (8,13): error CS0159: No such label 'A' within the scope of the goto statement // goto A; Diagnostic(ErrorCode.ERR_LabelNotFound, "goto").WithArguments("A").WithLocation(8, 13) ); } [Fact] public void BadDefiniteAssignmentCall() { var source = @" using System; class Program { static void A() { goto Label; int x = 2; void Local() { Console.Write(x); } Label: Local(); } static void Main(string[] args) { A(); } }"; VerifyDiagnostics(source, // (9,9): warning CS0162: Unreachable code detected // int x = 2; Diagnostic(ErrorCode.WRN_UnreachableCode, "int").WithLocation(9, 9), // (15,9): error CS0165: Use of unassigned local variable 'x' // Local(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Local()").WithArguments("x").WithLocation(15, 9) ); } [Fact] public void BadDefiniteAssignmentDelegateConversion() { var source = @" using System; class Program { static void A() { goto Label; int x = 2; void Local() { Console.Write(x); } Label: Action goo = Local; } static void Main(string[] args) { A(); } }"; VerifyDiagnostics(source, // (9,9): warning CS0162: Unreachable code detected // int x = 2; Diagnostic(ErrorCode.WRN_UnreachableCode, "int").WithLocation(9, 9), // (15,22): error CS0165: Use of unassigned local variable 'x' // Action goo = Local; Diagnostic(ErrorCode.ERR_UseDefViolation, "Local").WithArguments("x").WithLocation(15, 22) ); } [Fact] public void BadDefiniteAssignmentDelegateConstruction() { var source = @" using System; class Program { static void A() { goto Label; int x = 2; void Local() { Console.Write(x); } Label: var bar = new Action(Local); } static void Main(string[] args) { A(); } }"; VerifyDiagnostics(source, // (9,9): warning CS0162: Unreachable code detected // int x = 2; Diagnostic(ErrorCode.WRN_UnreachableCode, "int").WithLocation(9, 9), // (15,19): error CS0165: Use of unassigned local variable 'x' // var bar = new Action(Local); Diagnostic(ErrorCode.ERR_UseDefViolation, "new Action(Local)").WithArguments("x").WithLocation(15, 19) ); } [Fact] public void BadNotUsed() { var source = @" class Program { static void A() { void Local() { } } static void Main(string[] args) { A(); } }"; VerifyDiagnostics(source, // (6,14): warning CS8321: The local function 'Local' is declared but never used // void Local() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local").WithArguments("Local").WithLocation(6, 14) ); } [Fact] public void BadNotUsedSwitch() { var source = @" class Program { static void A() { switch (0) { case 0: void Local() { } break; } } static void Main(string[] args) { A(); } }"; VerifyDiagnostics(source, // (9,18): warning CS8321: The local function 'Local' is declared but never used // void Local() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local").WithArguments("Local").WithLocation(9, 18) ); } [Fact] public void BadByRefClosure() { var source = @" using System; class Program { static void A(ref int x) { void Local() { Console.WriteLine(x); } Local(); } static void Main() { } }"; VerifyDiagnostics(source, // (10,31): error CS1628: Cannot use ref or out parameter 'x' inside an anonymous method, lambda expression, query expression, or local function // Console.WriteLine(x); Diagnostic(ErrorCode.ERR_AnonDelegateCantUse, "x").WithArguments("x").WithLocation(10, 31) ); } [Fact] public void BadInClosure() { var source = @" using System; class Program { static void A(in int x) { void Local() { Console.WriteLine(x); } Local(); } static void Main() { } }"; VerifyDiagnostics(source, // (10,31): error CS1628: Cannot use ref, out, or in parameter 'x' inside an anonymous method, lambda expression, query expression, or local function // Console.WriteLine(x); Diagnostic(ErrorCode.ERR_AnonDelegateCantUse, "x").WithArguments("x").WithLocation(10, 31) ); } [Fact] public void BadArglistUse() { var source = @" using System; class Program { static void A() { void Local() { Console.WriteLine(__arglist); } Local(); } static void B(__arglist) { void Local() { Console.WriteLine(__arglist); } Local(); } static void C() // C and D produce different errors { void Local(__arglist) { Console.WriteLine(__arglist); } Local(__arglist()); } static void D(__arglist) { void Local(__arglist) { Console.WriteLine(__arglist); } Local(__arglist()); } static void Main() { } } "; VerifyDiagnostics(source, // (10,31): error CS0190: The __arglist construct is valid only within a variable argument method // Console.WriteLine(__arglist); Diagnostic(ErrorCode.ERR_ArgsInvalid, "__arglist").WithLocation(10, 31), // (18,31): error CS4013: Instance of type 'RuntimeArgumentHandle' cannot be used inside an anonymous function, query expression, iterator block or async method // Console.WriteLine(__arglist); Diagnostic(ErrorCode.ERR_SpecialByRefInLambda, "__arglist").WithArguments("System.RuntimeArgumentHandle").WithLocation(18, 31), // (24,20): error CS1669: __arglist is not valid in this context // void Local(__arglist) Diagnostic(ErrorCode.ERR_IllegalVarArgs, "__arglist").WithLocation(24, 20), // (26,31): error CS0190: The __arglist construct is valid only within a variable argument method // Console.WriteLine(__arglist); Diagnostic(ErrorCode.ERR_ArgsInvalid, "__arglist").WithLocation(26, 31), // (32,20): error CS1669: __arglist is not valid in this context // void Local(__arglist) Diagnostic(ErrorCode.ERR_IllegalVarArgs, "__arglist").WithLocation(32, 20), // (34,31): error CS4013: Instance of type 'RuntimeArgumentHandle' cannot be used inside an anonymous function, query expression, iterator block or async method // Console.WriteLine(__arglist); Diagnostic(ErrorCode.ERR_SpecialByRefInLambda, "__arglist").WithArguments("System.RuntimeArgumentHandle").WithLocation(34, 31) ); } [Fact] public void BadClosureStaticRefInstance() { var source = @" using System; class Program { int _a = 0; static void A() { void Local() { Console.WriteLine(_a); } Local(); } static void Main() { } } "; VerifyDiagnostics(source, // (11,31): error CS0120: An object reference is required for the non-static field, method, or property 'Program._a' // Console.WriteLine(_a); Diagnostic(ErrorCode.ERR_ObjectRequired, "_a").WithArguments("Program._a").WithLocation(11, 31) ); } [Fact] public void BadRefIterator() { var source = @" using System.Collections.Generic; class Program { static void Main(string[] args) { IEnumerable<int> RefEnumerable(ref int x) { yield return x; } int y = 0; RefEnumerable(ref y); } } "; VerifyDiagnostics(source, // (8,48): error CS1623: Iterators cannot have ref, in or out parameters // IEnumerable<int> RefEnumerable(ref int x) Diagnostic(ErrorCode.ERR_BadIteratorArgType, "x").WithLocation(8, 48) ); } [Fact] public void BadRefAsync() { var source = @" using System; using System.Threading.Tasks; class Program { static void Main(string[] args) { async Task<int> RefAsync(ref int x) { return await Task.FromResult(x); } int y = 2; Console.Write(RefAsync(ref y).Result); } } "; VerifyDiagnostics(source, // (9,42): error CS1988: Async methods cannot have ref, in or out parameters // async Task<int> RefAsync(ref int x) Diagnostic(ErrorCode.ERR_BadAsyncArgType, "x").WithLocation(9, 42) ); } [Fact] public void Extension_01() { var source = @" using System; class Program { static void Main(string[] args) { int Local(this int x) { return x; } Console.WriteLine(Local(2)); } } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (8,13): error CS1106: Extension method must be defined in a non-generic static class // int Local(this int x) Diagnostic(ErrorCode.ERR_BadExtensionAgg, "Local").WithLocation(8, 13) ); } [Fact] public void Extension_02() { var source = @"#pragma warning disable 8321 static class E { static void M() { void F1(this string s) { } static void F2(this string s) { } } }"; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (6,14): error CS1106: Extension method must be defined in a non-generic static class // void F1(this string s) { } Diagnostic(ErrorCode.ERR_BadExtensionAgg, "F1").WithLocation(6, 14), // (7,21): error CS1106: Extension method must be defined in a non-generic static class // static void F2(this string s) { } Diagnostic(ErrorCode.ERR_BadExtensionAgg, "F2").WithLocation(7, 21)); } [Fact] public void BadModifiers() { var source = @" class Program { static void Main(string[] args) { const void LocalConst() { } static void LocalStatic() { } readonly void LocalReadonly() { } volatile void LocalVolatile() { } LocalConst(); LocalStatic(); LocalReadonly(); LocalVolatile(); } } "; var baseExpected = new[] { // (6,9): error CS0106: The modifier 'const' is not valid for this item // const void LocalConst() Diagnostic(ErrorCode.ERR_BadMemberFlag, "const").WithArguments("const").WithLocation(6, 9), // (12,9): error CS0106: The modifier 'readonly' is not valid for this item // readonly void LocalReadonly() Diagnostic(ErrorCode.ERR_BadMemberFlag, "readonly").WithArguments("readonly").WithLocation(12, 9), // (15,9): error CS0106: The modifier 'volatile' is not valid for this item // volatile void LocalVolatile() Diagnostic(ErrorCode.ERR_BadMemberFlag, "volatile").WithArguments("volatile").WithLocation(15, 9) }; var extra = new[] { // (9,9): error CS8652: The feature 'static local functions' is not available in C# 7.3. Please use language version 8.0 or greater. // static void LocalStatic() Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "static").WithArguments("static local functions", "8.0").WithLocation(9, 9), }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics( baseExpected.Concat(extra).ToArray()); comp = CreateCompilation(source, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(baseExpected); comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(baseExpected); } [Fact] public void ArglistIterator() { var source = @" using System; using System.Collections.Generic; class Program { static void Main(string[] args) { IEnumerable<int> Local(__arglist) { yield return 2; } Console.WriteLine(string.Join("","", Local(__arglist()))); } } "; VerifyDiagnostics(source, // (9,26): error CS1636: __arglist is not allowed in the parameter list of iterators // IEnumerable<int> Local(__arglist) Diagnostic(ErrorCode.ERR_VarargsIterator, "Local").WithLocation(9, 26), // (9,32): error CS1669: __arglist is not valid in this context // IEnumerable<int> Local(__arglist) Diagnostic(ErrorCode.ERR_IllegalVarArgs, "__arglist").WithLocation(9, 32)); } [Fact] public void ForwardReference() { var source = @" using System; class Program { static void Main(string[] args) { Console.WriteLine(Local()); int Local() => 2; } } "; CompileAndVerify(source, expectedOutput: "2"); } [Fact] public void ForwardReferenceCapture() { var source = @" using System; class Program { static void Main(string[] args) { int x = 2; Console.WriteLine(Local()); int Local() => x; } } "; CompileAndVerify(source, expectedOutput: "2"); } [Fact] public void ForwardRefInLocalFunc() { var source = @" using System; class Program { static void Main(string[] args) { int x = 2; Console.WriteLine(Local()); int Local() { x = 3; return Local2(); } int Local2() => x; } } "; CompileAndVerify(source, expectedOutput: "3"); } [Fact] public void LocalFuncMutualRecursion() { var source = @" using System; class Program { static void Main(string[] args) { int x = 5; int y = 0; Console.WriteLine(Local1()); int Local1() { x -= 1; return Local2(y++); } int Local2(int z) { if (x == 0) { return z; } else { return Local1(); } } } } "; CompileAndVerify(source, expectedOutput: "4"); } [Fact] public void OtherSwitchBlock() { var source = @" using System; class Program { static void Main(string[] args) { var x = int.Parse(Console.ReadLine()); switch (x) { case 0: void Local() { } break; default: Local(); break; } } } "; VerifyDiagnostics(source); } [Fact] public void NoOperator() { var source = @" class Program { static void Main(string[] args) { Program operator +(Program left, Program right) { return left; } } } "; VerifyDiagnostics(source, // (6,17): error CS1002: ; expected // Program operator +(Program left, Program right) Diagnostic(ErrorCode.ERR_SemicolonExpected, "operator").WithLocation(6, 17), // (6,17): error CS1513: } expected // Program operator +(Program left, Program right) Diagnostic(ErrorCode.ERR_RbraceExpected, "operator").WithLocation(6, 17), // (6,56): error CS1002: ; expected // Program operator +(Program left, Program right) Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(6, 56), // (6,9): error CS0119: 'Program' is a type, which is not valid in the given context // Program operator +(Program left, Program right) Diagnostic(ErrorCode.ERR_BadSKunknown, "Program").WithArguments("Program", "type").WithLocation(6, 9), // (6,28): error CS8185: A declaration is not allowed in this context. // Program operator +(Program left, Program right) Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "Program left").WithLocation(6, 28), // (6,42): error CS8185: A declaration is not allowed in this context. // Program operator +(Program left, Program right) Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "Program right").WithLocation(6, 42), // (6,27): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported // Program operator +(Program left, Program right) Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(Program left, Program right)").WithArguments("System.ValueTuple`2").WithLocation(6, 27), // (8,13): error CS0127: Since 'Program.Main(string[])' returns void, a return keyword must not be followed by an object expression // return left; Diagnostic(ErrorCode.ERR_RetNoObjectRequired, "return").WithArguments("Program.Main(string[])").WithLocation(8, 13), // (6,28): error CS0165: Use of unassigned local variable 'left' // Program operator +(Program left, Program right) Diagnostic(ErrorCode.ERR_UseDefViolation, "Program left").WithArguments("left").WithLocation(6, 28), // (6,42): error CS0165: Use of unassigned local variable 'right' // Program operator +(Program left, Program right) Diagnostic(ErrorCode.ERR_UseDefViolation, "Program right").WithArguments("right").WithLocation(6, 42) ); } [Fact] public void NoProperty() { var source = @" class Program { static void Main(string[] args) { int Goo { get { return 2; } } int Bar => 2; } } "; VerifyDiagnostics(source, // (6,16): error CS1002: ; expected // int Goo Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(6, 16), // (8,16): error CS1002: ; expected // get Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(8, 16), // (13,17): error CS1003: Syntax error, ',' expected // int Bar => 2; Diagnostic(ErrorCode.ERR_SyntaxError, "=>").WithArguments(",", "=>").WithLocation(13, 17), // (13,20): error CS1002: ; expected // int Bar => 2; Diagnostic(ErrorCode.ERR_SemicolonExpected, "2").WithLocation(13, 20), // (8,13): error CS0103: The name 'get' does not exist in the current context // get Diagnostic(ErrorCode.ERR_NameNotInContext, "get").WithArguments("get").WithLocation(8, 13), // (10,17): error CS0127: Since 'Program.Main(string[])' returns void, a return keyword must not be followed by an object expression // return 2; Diagnostic(ErrorCode.ERR_RetNoObjectRequired, "return").WithArguments("Program.Main(string[])").WithLocation(10, 17), // (13,20): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // int Bar => 2; Diagnostic(ErrorCode.ERR_IllegalStatement, "2").WithLocation(13, 20), // (13,9): warning CS0162: Unreachable code detected // int Bar => 2; Diagnostic(ErrorCode.WRN_UnreachableCode, "int").WithLocation(13, 9), // (6,13): warning CS0168: The variable 'Goo' is declared but never used // int Goo Diagnostic(ErrorCode.WRN_UnreferencedVar, "Goo").WithArguments("Goo").WithLocation(6, 13), // (13,13): warning CS0168: The variable 'Bar' is declared but never used // int Bar => 2; Diagnostic(ErrorCode.WRN_UnreferencedVar, "Bar").WithArguments("Bar").WithLocation(13, 13) ); } [Fact] public void NoFeatureSwitch() { var source = @" class Program { static void Main(string[] args) { void Local() { } Local(); } } "; var option = TestOptions.ReleaseExe; CreateCompilation(source, options: option, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)).VerifyDiagnostics( // (6,14): error CS8059: Feature 'local functions' is not available in C# 6. Please use language version 7.0 or greater. // void Local() { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "Local").WithArguments("local functions", "7.0").WithLocation(6, 14) ); } [Fact, WorkItem(10521, "https://github.com/dotnet/roslyn/issues/10521")] public void LocalFunctionInIf() { var source = @" class Program { static void Main(string[] args) { if () // typing at this point int Add(int x, int y) => x + y; } } "; VerifyDiagnostics(source, // (6,13): error CS1525: Invalid expression term ')' // if () // typing at this point Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(6, 13), // (7,9): error CS1023: Embedded statement cannot be a declaration or labeled statement // int Add(int x, int y) => x + y; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "int Add(int x, int y) => x + y;").WithLocation(7, 9), // (7,13): warning CS8321: The local function 'Add' is declared but never used // int Add(int x, int y) => x + y; Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Add").WithArguments("Add").WithLocation(7, 13) ); } [Fact, WorkItem(10521, "https://github.com/dotnet/roslyn/issues/10521")] public void LabeledLocalFunctionInIf() { var source = @" class Program { static void Main(string[] args) { if () // typing at this point a: int Add(int x, int y) => x + y; } } "; VerifyDiagnostics(source, // (6,13): error CS1525: Invalid expression term ')' // if () // typing at this point Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(6, 13), // (7,1): error CS1023: Embedded statement cannot be a declaration or labeled statement // a: int Add(int x, int y) => x + y; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "a: int Add(int x, int y) => x + y;").WithLocation(7, 1), // (7,1): warning CS0164: This label has not been referenced // a: int Add(int x, int y) => x + y; Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(7, 1), // (7,13): warning CS8321: The local function 'Add' is declared but never used // a: int Add(int x, int y) => x + y; Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Add").WithArguments("Add").WithLocation(7, 13) ); } [CompilerTrait(CompilerFeature.LocalFunctions, CompilerFeature.Var)] public sealed class VarTests : LocalFunctionsTestBase { [Fact] public void IllegalAsReturn() { var source = @" using System; class Program { static void Main() { var f() => 42; Console.WriteLine(f()); } }"; var comp = CreateCompilationWithMscorlib45(source, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (7,9): error CS0825: The contextual keyword 'var' may only appear within a local variable declaration or in script code // var f() => 42; Diagnostic(ErrorCode.ERR_TypeVarNotFound, "var").WithLocation(7, 9)); } [Fact] public void RealTypeAsReturn() { var source = @" using System; class var { public override string ToString() => ""dog""; } class Program { static void Main() { var f() => new var(); Console.WriteLine(f()); } }"; CompileAndVerify( source, parseOptions: DefaultParseOptions, expectedOutput: "dog"); } [Fact] public void RealTypeParameterAsReturn() { var source = @" using System; class test { public override string ToString() => ""dog""; } class Program { static void Test<var>(var x) { var f() => x; Console.WriteLine(f()); } static void Main() { Test(new test()); } }"; CompileAndVerify( source, parseOptions: DefaultParseOptions, expectedOutput: "dog"); } [Fact] public void IdentifierAndTypeNamedVar() { var source = @" using System; class var { public override string ToString() => ""dog""; } class Program { static void Main() { int var = 42; var f() => new var(); Console.WriteLine($""{f()}-{var}""); } }"; CompileAndVerify( source, parseOptions: DefaultParseOptions, expectedOutput: "dog-42"); } } [CompilerTrait(CompilerFeature.LocalFunctions, CompilerFeature.Async)] public sealed class AsyncTests : LocalFunctionsTestBase { [Fact] public void RealTypeAsReturn() { var source = @" using System; class async { public override string ToString() => ""dog""; } class Program { static void Main() { async f() => new async(); Console.WriteLine(f()); } }"; CompileAndVerify( source, parseOptions: DefaultParseOptions, expectedOutput: "dog"); } [Fact] public void RealTypeParameterAsReturn() { var source = @" using System; class test { public override string ToString() => ""dog""; } class Program { static void Test<async>(async x) { async f() => x; Console.WriteLine(f()); } static void Main() { Test(new test()); } }"; CompileAndVerify( source, parseOptions: DefaultParseOptions, expectedOutput: "dog"); } [Fact] public void ManyMeaningsType() { var source = @" using System; using System.Threading; using System.Threading.Tasks; class async { public override string ToString() => ""async""; } class Program { static void Main() { async Task<async> Test(Task<async> t) { async local = await t; Console.WriteLine(local); return local; } Test(Task.FromResult<async>(new async())).Wait(); } }"; var comp = CreateCompilationWithMscorlib46(source, parseOptions: DefaultParseOptions, options: TestOptions.DebugExe); CompileAndVerify( comp, expectedOutput: "async"); } } [Fact] [WorkItem(12467, "https://github.com/dotnet/roslyn/issues/12467")] public void ParamUnassigned_01() { var src = @" class C { public void M1() { void TakeOutParam1(out int x) { } int y; TakeOutParam1(out y); } void TakeOutParam2(out int x) { } }"; VerifyDiagnostics(src, // (6,14): error CS0177: The out parameter 'x' must be assigned to before control leaves the current method // void TakeOutParam1(out int x) Diagnostic(ErrorCode.ERR_ParamUnassigned, "TakeOutParam1").WithArguments("x").WithLocation(6, 14), // (14,14): error CS0177: The out parameter 'x' must be assigned to before control leaves the current method // void TakeOutParam2(out int x) Diagnostic(ErrorCode.ERR_ParamUnassigned, "TakeOutParam2").WithArguments("x").WithLocation(14, 14) ); } [Fact] [WorkItem(12467, "https://github.com/dotnet/roslyn/issues/12467")] public void ParamUnassigned_02() { var src = @" class C { public void M1() { void TakeOutParam1(out int x) { return; // 1 } int y; TakeOutParam1(out y); } void TakeOutParam2(out int x) { return; // 2 } }"; VerifyDiagnostics(src, // (8,13): error CS0177: The out parameter 'x' must be assigned to before control leaves the current method // return; // 1 Diagnostic(ErrorCode.ERR_ParamUnassigned, "return;").WithArguments("x").WithLocation(8, 13), // (17,13): error CS0177: The out parameter 'x' must be assigned to before control leaves the current method // return; // 2 Diagnostic(ErrorCode.ERR_ParamUnassigned, "return;").WithArguments("x").WithLocation(17, 13) ); } [Fact] [WorkItem(12467, "https://github.com/dotnet/roslyn/issues/12467")] public void ParamUnassigned_03() { var src = @" class C { public void M1() { int TakeOutParam1(out int x) { } int y; TakeOutParam1(out y); } int TakeOutParam2(out int x) { } }"; VerifyDiagnostics(src, // (6,13): error CS0161: 'TakeOutParam1(out int)': not all code paths return a value // int TakeOutParam1(out int x) Diagnostic(ErrorCode.ERR_ReturnExpected, "TakeOutParam1").WithArguments("TakeOutParam1(out int)").WithLocation(6, 13), // (6,13): error CS0177: The out parameter 'x' must be assigned to before control leaves the current method // int TakeOutParam1(out int x) Diagnostic(ErrorCode.ERR_ParamUnassigned, "TakeOutParam1").WithArguments("x").WithLocation(6, 13), // (14,13): error CS0177: The out parameter 'x' must be assigned to before control leaves the current method // int TakeOutParam2(out int x) Diagnostic(ErrorCode.ERR_ParamUnassigned, "TakeOutParam2").WithArguments("x").WithLocation(14, 13), // (14,13): error CS0161: 'C.TakeOutParam2(out int)': not all code paths return a value // int TakeOutParam2(out int x) Diagnostic(ErrorCode.ERR_ReturnExpected, "TakeOutParam2").WithArguments("C.TakeOutParam2(out int)").WithLocation(14, 13) ); } [Fact] [WorkItem(12467, "https://github.com/dotnet/roslyn/issues/12467")] public void ParamUnassigned_04() { var src = @" class C { public void M1() { int TakeOutParam1(out int x) { return 1; } int y; TakeOutParam1(out y); } int TakeOutParam2(out int x) { return 2; } }"; VerifyDiagnostics(src, // (8,13): error CS0177: The out parameter 'x' must be assigned to before control leaves the current method // return 1; Diagnostic(ErrorCode.ERR_ParamUnassigned, "return 1;").WithArguments("x").WithLocation(8, 13), // (17,13): error CS0177: The out parameter 'x' must be assigned to before control leaves the current method // return 2; Diagnostic(ErrorCode.ERR_ParamUnassigned, "return 2;").WithArguments("x").WithLocation(17, 13) ); } [Fact] [WorkItem(49500, "https://github.com/dotnet/roslyn/issues/49500")] public void OutParam_Extern_01() { var src = @" using System.Runtime.InteropServices; class C { void M() { int x; local(out x); x.ToString(); [DllImport(""a"")] static extern void local(out int x); } [DllImport(""a"")] static extern void Method(out int x); }"; VerifyDiagnostics(src); } [Fact] [WorkItem(49500, "https://github.com/dotnet/roslyn/issues/49500")] public void OutParam_Extern_02() { var src = @" using System.Runtime.InteropServices; class C { void M() { local1(out _); local2(out _); local3(out _); [DllImport(""a"")] static extern void local1(out int x) { } // 1 static void local2(out int x) { } // 2 static void local3(out int x); // 3, 4 } [DllImport(""a"")] static extern void Method(out int x); }"; VerifyDiagnostics(src, // (13,28): error CS0179: 'local1(out int)' cannot be extern and declare a body // static extern void local1(out int x) { } // 1 Diagnostic(ErrorCode.ERR_ExternHasBody, "local1").WithArguments("local1(out int)").WithLocation(13, 28), // (15,21): error CS0177: The out parameter 'x' must be assigned to before control leaves the current method // static void local2(out int x) { } // 2 Diagnostic(ErrorCode.ERR_ParamUnassigned, "local2").WithArguments("x").WithLocation(15, 21), // (17,21): error CS8112: Local function 'local3(out int)' must declare a body because it is not marked 'static extern'. // static void local3(out int x); // 3, 4 Diagnostic(ErrorCode.ERR_LocalFunctionMissingBody, "local3").WithArguments("local3(out int)").WithLocation(17, 21), // (17,21): error CS0177: The out parameter 'x' must be assigned to before control leaves the current method // static void local3(out int x); // 3, 4 Diagnostic(ErrorCode.ERR_ParamUnassigned, "local3").WithArguments("x").WithLocation(17, 21)); } [Fact] [WorkItem(13172, "https://github.com/dotnet/roslyn/issues/13172")] public void InheritUnsafeContext() { var comp = CreateCompilationWithMscorlib46(@" using System; using System.Threading.Tasks; class C { public void M1() { async Task<IntPtr> Local() { await Task.Delay(0); return (IntPtr)(void*)null; } var _ = Local(); } public void M2() { unsafe { async Task<IntPtr> Local() { await Task.Delay(1); return (IntPtr)(void*)null; } var _ = Local(); } } public unsafe void M3() { async Task<IntPtr> Local() { await Task.Delay(2); return (IntPtr)(void*)null; } var _ = Local(); } } unsafe class D { int* p = null; public void M() { async Task<IntPtr> Local() { await Task.Delay(3); return (IntPtr)p; } var _ = Local(); } public unsafe void M2() { unsafe { async Task<IntPtr> Local() { await Task.Delay(4); return (IntPtr)(void*)null; } var _ = Local(); } } }", options: TestOptions.UnsafeDebugDll); comp.VerifyDiagnostics( // (11,29): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // return (IntPtr)(void*)null; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "void*").WithLocation(11, 29), // (11,28): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // return (IntPtr)(void*)null; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "(void*)null").WithLocation(11, 28), // (47,13): error CS4004: Cannot await in an unsafe context // await Task.Delay(3); Diagnostic(ErrorCode.ERR_AwaitInUnsafeContext, "await Task.Delay(3)").WithLocation(47, 13), // (22,17): error CS4004: Cannot await in an unsafe context // await Task.Delay(1); Diagnostic(ErrorCode.ERR_AwaitInUnsafeContext, "await Task.Delay(1)").WithLocation(22, 17), // (59,17): error CS4004: Cannot await in an unsafe context // await Task.Delay(4); Diagnostic(ErrorCode.ERR_AwaitInUnsafeContext, "await Task.Delay(4)").WithLocation(59, 17), // (33,13): error CS4004: Cannot await in an unsafe context // await Task.Delay(2); Diagnostic(ErrorCode.ERR_AwaitInUnsafeContext, "await Task.Delay(2)").WithLocation(33, 13)); } [Fact, WorkItem(16167, "https://github.com/dotnet/roslyn/issues/16167")] public void DeclarationInLocalFunctionParameterDefault() { var text = @" class C { public static void Main(int arg) { void Local1(bool b = M(arg is int z1, z1), int s1 = z1) {} void Local2(bool b = M(M(out int z2), z2), int s2 = z2) {} void Local3(bool b = M(M((int z3, int a2) = (1, 2)), z3), int a3 = z3) {} void Local4(bool b = M(arg is var z4, z4), int s1 = z4) {} void Local5(bool b = M(M(out var z5), z5), int s2 = z5) {} void Local6(bool b = M(M((var z6, int a2) = (1, 2)), z6), int a3 = z6) {} int t = z1 + z2 + z3 + z4 + z5 + z6; } static bool M(out int z) // needed to infer type of z5 { z = 1; return true; } static bool M(params object[] args) => true; } namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { Item1 = item1; Item2 = item2; } } } "; // the scope of an expression variable introduced in the default expression // of a local function parameter is that default expression. var compilation = CreateCompilationWithMscorlib45(text); compilation.VerifyDiagnostics( // (6,30): error CS1736: Default parameter value for 'b' must be a compile-time constant // void Local1(bool b = M(arg is int z1, z1), int s1 = z1) {} Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "M(arg is int z1, z1)").WithArguments("b").WithLocation(6, 30), // (6,61): error CS0103: The name 'z1' does not exist in the current context // void Local1(bool b = M(arg is int z1, z1), int s1 = z1) {} Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(6, 61), // (7,30): error CS1736: Default parameter value for 'b' must be a compile-time constant // void Local2(bool b = M(M(out int z2), z2), int s2 = z2) {} Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "M(M(out int z2), z2)").WithArguments("b").WithLocation(7, 30), // (7,61): error CS0103: The name 'z2' does not exist in the current context // void Local2(bool b = M(M(out int z2), z2), int s2 = z2) {} Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(7, 61), // (8,35): error CS8185: A declaration is not allowed in this context. // void Local3(bool b = M(M((int z3, int a2) = (1, 2)), z3), int a3 = z3) {} Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int z3").WithLocation(8, 35), // (8,30): error CS1736: Default parameter value for 'b' must be a compile-time constant // void Local3(bool b = M(M((int z3, int a2) = (1, 2)), z3), int a3 = z3) {} Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "M(M((int z3, int a2) = (1, 2)), z3)").WithArguments("b").WithLocation(8, 30), // (8,76): error CS0103: The name 'z3' does not exist in the current context // void Local3(bool b = M(M((int z3, int a2) = (1, 2)), z3), int a3 = z3) {} Diagnostic(ErrorCode.ERR_NameNotInContext, "z3").WithArguments("z3").WithLocation(8, 76), // (10,30): error CS1736: Default parameter value for 'b' must be a compile-time constant // void Local4(bool b = M(arg is var z4, z4), int s1 = z4) {} Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "M(arg is var z4, z4)").WithArguments("b").WithLocation(10, 30), // (10,61): error CS0103: The name 'z4' does not exist in the current context // void Local4(bool b = M(arg is var z4, z4), int s1 = z4) {} Diagnostic(ErrorCode.ERR_NameNotInContext, "z4").WithArguments("z4").WithLocation(10, 61), // (11,30): error CS1736: Default parameter value for 'b' must be a compile-time constant // void Local5(bool b = M(M(out var z5), z5), int s2 = z5) {} Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "M(M(out var z5), z5)").WithArguments("b").WithLocation(11, 30), // (11,61): error CS0103: The name 'z5' does not exist in the current context // void Local5(bool b = M(M(out var z5), z5), int s2 = z5) {} Diagnostic(ErrorCode.ERR_NameNotInContext, "z5").WithArguments("z5").WithLocation(11, 61), // (12,35): error CS8185: A declaration is not allowed in this context. // void Local6(bool b = M(M((var z6, int a2) = (1, 2)), z6), int a3 = z6) {} Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var z6").WithLocation(12, 35), // (12,30): error CS1736: Default parameter value for 'b' must be a compile-time constant // void Local6(bool b = M(M((var z6, int a2) = (1, 2)), z6), int a3 = z6) {} Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "M(M((var z6, int a2) = (1, 2)), z6)").WithArguments("b").WithLocation(12, 30), // (12,76): error CS0103: The name 'z6' does not exist in the current context // void Local6(bool b = M(M((var z6, int a2) = (1, 2)), z6), int a3 = z6) {} Diagnostic(ErrorCode.ERR_NameNotInContext, "z6").WithArguments("z6").WithLocation(12, 76), // (14,17): error CS0103: The name 'z1' does not exist in the current context // int t = z1 + z2 + z3 + z4 + z5 + z6; Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(14, 17), // (14,22): error CS0103: The name 'z2' does not exist in the current context // int t = z1 + z2 + z3 + z4 + z5 + z6; Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(14, 22), // (14,27): error CS0103: The name 'z3' does not exist in the current context // int t = z1 + z2 + z3 + z4 + z5 + z6; Diagnostic(ErrorCode.ERR_NameNotInContext, "z3").WithArguments("z3").WithLocation(14, 27), // (14,32): error CS0103: The name 'z4' does not exist in the current context // int t = z1 + z2 + z3 + z4 + z5 + z6; Diagnostic(ErrorCode.ERR_NameNotInContext, "z4").WithArguments("z4").WithLocation(14, 32), // (14,37): error CS0103: The name 'z5' does not exist in the current context // int t = z1 + z2 + z3 + z4 + z5 + z6; Diagnostic(ErrorCode.ERR_NameNotInContext, "z5").WithArguments("z5").WithLocation(14, 37), // (14,42): error CS0103: The name 'z6' does not exist in the current context // int t = z1 + z2 + z3 + z4 + z5 + z6; Diagnostic(ErrorCode.ERR_NameNotInContext, "z6").WithArguments("z6").WithLocation(14, 42), // (6,14): warning CS8321: The local function 'Local1' is declared but never used // void Local1(bool b = M(arg is int z1, z1), int s1 = z1) {} Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local1").WithArguments("Local1").WithLocation(6, 14), // (7,14): warning CS8321: The local function 'Local2' is declared but never used // void Local2(bool b = M(M(out int z2), z2), int s2 = z2) {} Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local2").WithArguments("Local2").WithLocation(7, 14), // (8,14): warning CS8321: The local function 'Local3' is declared but never used // void Local3(bool b = M(M((int z3, int a2) = (1, 2)), z3), int a3 = z3) {} Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local3").WithArguments("Local3").WithLocation(8, 14), // (10,14): warning CS8321: The local function 'Local4' is declared but never used // void Local4(bool b = M(arg is var z4, z4), int s1 = z4) {} Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local4").WithArguments("Local4").WithLocation(10, 14), // (11,14): warning CS8321: The local function 'Local5' is declared but never used // void Local5(bool b = M(M(out var z5), z5), int s2 = z5) {} Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local5").WithArguments("Local5").WithLocation(11, 14), // (12,14): warning CS8321: The local function 'Local6' is declared but never used // void Local6(bool b = M(M((var z6, int a2) = (1, 2)), z6), int a3 = z6) {} Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local6").WithArguments("Local6").WithLocation(12, 14) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var descendents = tree.GetRoot().DescendantNodes(); for (int i = 1; i <= 6; i++) { var name = $"z{i}"; var designation = descendents.OfType<SingleVariableDesignationSyntax>().Where(d => d.Identifier.ValueText == name).Single(); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(designation); Assert.NotNull(symbol); Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString()); var refs = descendents.OfType<IdentifierNameSyntax>().Where(n => n.Identifier.ValueText == name).ToArray(); Assert.Equal(3, refs.Length); Assert.Equal(symbol, model.GetSymbolInfo(refs[0]).Symbol); Assert.Null(model.GetSymbolInfo(refs[1]).Symbol); Assert.Null(model.GetSymbolInfo(refs[2]).Symbol); } } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/16451")] public void RecursiveParameterDefault() { var text = @" class C { public static void Main(int arg) { int Local(int x = Local()) => 2; } } "; var compilation = CreateCompilationWithMscorlib45(text); compilation.VerifyDiagnostics( ); } [Fact] [WorkItem(16757, "https://github.com/dotnet/roslyn/issues/16757")] public void LocalFunctionParameterDefaultUsingConst() { var source = @" class C { public static void Main() { const int N = 2; void Local1(int n = N) { System.Console.Write(n); } Local1(); Local1(3); } } "; CompileAndVerify(source, expectedOutput: "23", sourceSymbolValidator: m => { var compilation = m.DeclaringCompilation; // See https://github.com/dotnet/roslyn/issues/16454; this should actually produce no errors compilation.VerifyDiagnostics( // (6,19): warning CS0219: The variable 'N' is assigned but its value is never used // const int N = 2; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "N").WithArguments("N").WithLocation(6, 19) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var descendents = tree.GetRoot().DescendantNodes(); var parameter = descendents.OfType<ParameterSyntax>().Single(); Assert.Equal("int n = N", parameter.ToString()); Assert.Equal("[System.Int32 n = 2]", model.GetDeclaredSymbol(parameter).ToTestDisplayString()); var name = "N"; var declarator = descendents.OfType<VariableDeclaratorSyntax>().Where(d => d.Identifier.ValueText == name).Single(); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(declarator); Assert.NotNull(symbol); Assert.Equal("System.Int32 N", symbol.ToTestDisplayString()); var refs = descendents.OfType<IdentifierNameSyntax>().Where(n => n.Identifier.ValueText == name).ToArray(); Assert.Equal(1, refs.Length); Assert.Same(symbol, model.GetSymbolInfo(refs[0]).Symbol); }); } [Fact] [WorkItem(15536, "https://github.com/dotnet/roslyn/issues/15536")] public void CallFromDifferentSwitchSection_01() { var source = @" class Program { static void Main() { Test(string.Empty); } static void Test(object o) { switch (o) { case string x: Assign(); Print(); break; case int x: void Assign() { x = 5; } void Print() => System.Console.WriteLine(x); break; } } }"; var comp = CreateCompilationWithMscorlib46(source, parseOptions: DefaultParseOptions, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: "5"); } [Fact] [WorkItem(15536, "https://github.com/dotnet/roslyn/issues/15536")] public void CallFromDifferentSwitchSection_02() { var source = @" class Program { static void Main() { Test(string.Empty); } static void Test(object o) { switch (o) { case int x: void Assign() { x = 5; } void Print() => System.Console.WriteLine(x); break; case string x: Assign(); Print(); break; } } }"; var comp = CreateCompilationWithMscorlib46(source, parseOptions: DefaultParseOptions, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: "5"); } [Fact] [WorkItem(15536, "https://github.com/dotnet/roslyn/issues/15536")] public void CallFromDifferentSwitchSection_03() { var source = @" class Program { static void Main() { Test(string.Empty); } static void Test(object o) { switch (o) { case string x: Assign(); System.Action p = Print; p(); break; case int x: void Assign() { x = 5; } void Print() => System.Console.WriteLine(x); break; } } }"; var comp = CreateCompilationWithMscorlib46(source, parseOptions: DefaultParseOptions, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: "5"); } [Fact] [WorkItem(15536, "https://github.com/dotnet/roslyn/issues/15536")] public void CallFromDifferentSwitchSection_04() { var source = @" class Program { static void Main() { Test(string.Empty); } static void Test(object o) { switch (o) { case int x: void Assign() { x = 5; } void Print() => System.Console.WriteLine(x); break; case string x: Assign(); System.Action p = Print; p(); break; } } }"; var comp = CreateCompilationWithMscorlib46(source, parseOptions: DefaultParseOptions, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: "5"); } [Fact] [WorkItem(15536, "https://github.com/dotnet/roslyn/issues/15536")] public void CallFromDifferentSwitchSection_05() { var source = @" class Program { static void Main() { Test(string.Empty); } static void Test(object o) { switch (o) { case string x: Local1(); break; case int x: void Local1() => Local2(x = 5); break; case char x: void Local2(int y) { System.Console.WriteLine(x = 'a'); System.Console.WriteLine(y); } break; } } }"; var comp = CreateCompilationWithMscorlib46(source, parseOptions: DefaultParseOptions, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: @"a 5"); } [Fact] [WorkItem(16751, "https://github.com/dotnet/roslyn/issues/16751")] public void SemanticModelInAttribute_01() { var source = @" public class X { public static void Main() { const bool b1 = true; void Local1( [Test(p = b1)] [Test(p = b2)] int p1) { } Local1(1); } } class b1 {} class Test : System.Attribute { public bool p {get; set;} } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (10,23): error CS0103: The name 'b2' does not exist in the current context // [Test(p = b2)] Diagnostic(ErrorCode.ERR_NameNotInContext, "b2").WithArguments("b2").WithLocation(10, 23), // (6,20): warning CS0219: The variable 'b1' is assigned but its value is never used // const bool b1 = true; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "b1").WithArguments("b1").WithLocation(6, 20) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var b2 = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "b2").Single(); Assert.Null(model.GetSymbolInfo(b2).Symbol); var b1 = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "b1").Single(); var b1Symbol = model.GetSymbolInfo(b1).Symbol; Assert.Equal("System.Boolean b1", b1Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, b1Symbol.Kind); } [Fact] [WorkItem(19778, "https://github.com/dotnet/roslyn/issues/19778")] public void BindDynamicInvocation() { var source = @"using System; class C { static void M() { dynamic L<T>(Func<dynamic, T> t, object p) => p; L(m => L(d => d, null), null); L(m => L(d => d, m), null); } }"; var comp = CreateCompilationWithMscorlib45(source, references: new[] { SystemCoreRef, CSharpRef }); comp.VerifyEmitDiagnostics( // (8,18): error CS1977: Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type. // L(m => L(d => d, m), null); Diagnostic(ErrorCode.ERR_BadDynamicMethodArgLambda, "d => d").WithLocation(8, 18), // (8,16): error CS8322: Cannot pass argument with dynamic type to generic local function 'L' with inferred type arguments. // L(m => L(d => d, m), null); Diagnostic(ErrorCode.ERR_DynamicLocalFunctionTypeParameter, "L(d => d, m)").WithArguments("L").WithLocation(8, 16)); } [Fact] [WorkItem(19778, "https://github.com/dotnet/roslyn/issues/19778")] public void BindDynamicInvocation_Async() { var source = @"using System; using System.Threading.Tasks; class C { static void M() { async Task<dynamic> L<T>(Func<dynamic, T> t, object p) => await L(async m => L(async d => await d, m), p); } }"; var comp = CreateCompilationWithMscorlib45(source, references: new[] { SystemCoreRef, CSharpRef }); comp.VerifyEmitDiagnostics( // (8,37): error CS1977: Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type. // => await L(async m => L(async d => await d, m), p); Diagnostic(ErrorCode.ERR_BadDynamicMethodArgLambda, "async d => await d").WithLocation(8, 37), // (8,35): error CS8322: Cannot pass argument with dynamic type to generic local function 'L' with inferred type arguments. // => await L(async m => L(async d => await d, m), p); Diagnostic(ErrorCode.ERR_DynamicLocalFunctionTypeParameter, "L(async d => await d, m)").WithArguments("L").WithLocation(8, 35), // (8,32): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread. // => await L(async m => L(async d => await d, m), p); Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "=>").WithLocation(8, 32)); } [Fact] [WorkItem(21317, "https://github.com/dotnet/roslyn/issues/21317")] [CompilerTrait(CompilerFeature.Dynamic)] public void DynamicGenericArg() { var src = @" using System.Collections.Generic; class C { static void M() { dynamic val = 2; dynamic dynamicList = new List<int>(); void L1<T>(T x) { } L1(val); void L2<T>(int x, T y) { } L2(1, val); L2(val, 3.0f); void L3<T>(List<T> x) { } L3(dynamicList); void L4<T>(int x, params T[] y) { } L4(1, 2, val); L4(val, 3, 4); void L5<T>(T x, params int[] y) { } L5(val, 1, 2); L5(1, 3, val); } } "; VerifyDiagnostics(src, // (11,9): error CS8322: Cannot pass argument with dynamic type to generic local function 'L1'. Try specifying the type arguments explicitly. // L1(val); Diagnostic(ErrorCode.ERR_DynamicLocalFunctionTypeParameter, "L1(val)").WithArguments("L1").WithLocation(11, 9), // (14,9): error CS8322: Cannot pass argument with dynamic type to generic local function 'L2'. Try specifying the type arguments explicitly. // L2(1, val); Diagnostic(ErrorCode.ERR_DynamicLocalFunctionTypeParameter, "L2(1, val)").WithArguments("L2").WithLocation(14, 9), // (15,9): error CS8322: Cannot pass argument with dynamic type to generic local function 'L2'. Try specifying the type arguments explicitly. // L2(val, 3.0f); Diagnostic(ErrorCode.ERR_DynamicLocalFunctionTypeParameter, "L2(val, 3.0f)").WithArguments("L2").WithLocation(15, 9), // (18,9): error CS8322: Cannot pass argument with dynamic type to generic local function 'L3'. Try specifying the type arguments explicitly. // L3(dynamicList); Diagnostic(ErrorCode.ERR_DynamicLocalFunctionTypeParameter, "L3(dynamicList)").WithArguments("L3").WithLocation(18, 9), // (21,9): error CS8322: Cannot pass argument with dynamic type to generic local function 'L4'. Try specifying the type arguments explicitly. // L4(1, 2, val); Diagnostic(ErrorCode.ERR_DynamicLocalFunctionTypeParameter, "L4(1, 2, val)").WithArguments("L4").WithLocation(21, 9), // (22,9): error CS8322: Cannot pass argument with dynamic type to generic local function 'L4'. Try specifying the type arguments explicitly. // L4(val, 3, 4); Diagnostic(ErrorCode.ERR_DynamicLocalFunctionTypeParameter, "L4(val, 3, 4)").WithArguments("L4").WithLocation(22, 9), // (25,9): error CS8322: Cannot pass argument with dynamic type to generic local function 'L5'. Try specifying the type arguments explicitly. // L5(val, 1, 2); Diagnostic(ErrorCode.ERR_DynamicLocalFunctionTypeParameter, "L5(val, 1, 2)").WithArguments("L5").WithLocation(25, 9), // (26,9): error CS8322: Cannot pass argument with dynamic type to generic local function 'L5'. Try specifying the type arguments explicitly. // L5(1, 3, val); Diagnostic(ErrorCode.ERR_DynamicLocalFunctionTypeParameter, "L5(1, 3, val)").WithArguments("L5").WithLocation(26, 9) ); } [Fact] [WorkItem(23699, "https://github.com/dotnet/roslyn/issues/23699")] public void GetDeclaredSymbolOnTypeParameter() { var src = @" class C<T> { void M<U>() { void LocalFunction<T, U, V>(T p1, U p2, V p3) { } } } "; var comp = CreateCompilation(src); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var localDecl = (LocalFunctionStatementSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.LocalFunctionStatement).AsNode(); var typeParameters = localDecl.TypeParameterList.Parameters; var parameters = localDecl.ParameterList.Parameters; verifyTypeParameterAndParameter(typeParameters[0], parameters[0], "T"); verifyTypeParameterAndParameter(typeParameters[1], parameters[1], "U"); verifyTypeParameterAndParameter(typeParameters[2], parameters[2], "V"); void verifyTypeParameterAndParameter(TypeParameterSyntax typeParameter, ParameterSyntax parameter, string expected) { var symbol = model.GetDeclaredSymbol(typeParameter); Assert.Equal(expected, symbol.ToTestDisplayString()); var parameterSymbol = model.GetDeclaredSymbol(parameter); Assert.Equal(expected, parameterSymbol.Type.ToTestDisplayString()); Assert.Same(symbol, parameterSymbol.Type); } } public sealed class ScriptGlobals { public int SomeGlobal => 42; } [ConditionalFact(typeof(DesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/28001")] public void CanAccessScriptGlobalsFromInsideMethod() { var source = @" void Method() { LocalFunction(); void LocalFunction() { _ = SomeGlobal; } }"; CreateSubmission(source, new[] { ScriptTestFixtures.HostRef }, hostObjectType: typeof(ScriptGlobals)) .VerifyEmitDiagnostics(); } [ConditionalFact(typeof(DesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/28001")] public void CanAccessScriptGlobalsFromInsideLambda() { var source = @" var lambda = new System.Action(() => { LocalFunction(); void LocalFunction() { _ = SomeGlobal; } });"; CreateSubmission(source, new[] { ScriptTestFixtures.HostRef }, hostObjectType: typeof(ScriptGlobals)) .VerifyEmitDiagnostics(); } [Fact] public void CanAccessPreviousSubmissionVariablesFromInsideMethod() { var previous = CreateSubmission("int previousSubmissionVariable = 42;") .VerifyEmitDiagnostics(); var source = @" void Method() { LocalFunction(); void LocalFunction() { _ = previousSubmissionVariable; } }"; CreateSubmission(source, previous: previous) .VerifyEmitDiagnostics(); } [Fact] public void CanAccessPreviousSubmissionVariablesFromInsideLambda() { var previous = CreateSubmission("int previousSubmissionVariable = 42;") .VerifyEmitDiagnostics(); var source = @" var lambda = new System.Action(() => { LocalFunction(); void LocalFunction() { _ = previousSubmissionVariable; } });"; CreateSubmission(source, previous: previous) .VerifyEmitDiagnostics(); } [Fact] public void CanAccessPreviousSubmissionMethodsFromInsideMethod() { var previous = CreateSubmission("void PreviousSubmissionMethod() { }") .VerifyEmitDiagnostics(); var source = @" void Method() { LocalFunction(); void LocalFunction() { PreviousSubmissionMethod(); } }"; CreateSubmission(source, previous: previous) .VerifyEmitDiagnostics(); } [Fact] public void CanAccessPreviousSubmissionMethodsFromInsideLambda() { var previous = CreateSubmission("void PreviousSubmissionMethod() { }") .VerifyEmitDiagnostics(); var source = @" var lambda = new System.Action(() => { LocalFunction(); void LocalFunction() { PreviousSubmissionMethod(); } });"; CreateSubmission(source, previous: previous) .VerifyEmitDiagnostics(); } [Fact] public void ShadowNames_01() { var source = @"#pragma warning disable 0219 #pragma warning disable 8321 class Program { static void M() { void F1(object x) { string x = null; } // local void F2(object x, string y, int x) { } // parameter void F3(object x) { void x() { } } // method void F4<x, y>(object x) { void y() { } } // type parameter void F5(object M, string Program) { } } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3); verifyDiagnostics(); comp = CreateCompilation(source, parseOptions: TestOptions.Regular8); verifyDiagnostics(); comp = CreateCompilation(source); verifyDiagnostics(); void verifyDiagnostics() { comp.VerifyDiagnostics( // (7,36): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // void F1(object x) { string x = null; } // local Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(7, 36), // (8,41): error CS0100: The parameter name 'x' is a duplicate // void F2(object x, string y, int x) { } // parameter Diagnostic(ErrorCode.ERR_DuplicateParamName, "x").WithArguments("x").WithLocation(8, 41), // (9,34): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // void F3(object x) { void x() { } } // method Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(9, 34), // (10,30): error CS0412: 'x': a parameter, local variable, or local function cannot have the same name as a method type parameter // void F4<x, y>(object x) { void y() { } } // type parameter Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "x").WithArguments("x").WithLocation(10, 30), // (10,40): error CS0412: 'y': a parameter, local variable, or local function cannot have the same name as a method type parameter // void F4<x, y>(object x) { void y() { } } // type parameter Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "y").WithArguments("y").WithLocation(10, 40)); } } [Fact] public void ShadowNames_Local_01() { var source = @"#pragma warning disable 0219 #pragma warning disable 8321 using System.Linq; class Program { static void M() { object x = null; void F1() { object x = 0; } // local void F2(string x) { } // parameter void F3() { void x() { } } // method void F4<x>() { } // type parameter void F5() { _ = from x in new[] { 1, 2, 3 } select x; } // range variable } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics( // (9,28): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // void F1() { object x = 0; } // local Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(9, 28), // (10,24): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // void F2(string x) { } // parameter Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(10, 24), // (11,26): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // void F3() { void x() { } } // method Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(11, 26), // (12,17): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // void F4<x>() { } // type parameter Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(12, 17), // (13,30): error CS1931: The range variable 'x' conflicts with a previous declaration of 'x' // void F5() { _ = from x in new[] { 1, 2, 3 } select x; } // range variable Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "x").WithArguments("x").WithLocation(13, 30)); comp = CreateCompilation(source, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void ShadowNames_Local_02() { var source = @"#pragma warning disable 0219 #pragma warning disable 8321 using System.Linq; class Program { static void M() { void F1() { object x = 0; } // local void F2(string x) { } // parameter void F3() { void x() { } } // method void F4<x>() { } // type parameter void F5() { _ = from x in new[] { 1, 2, 3 } select x; } // range variable object x = null; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics( // (8,28): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // void F1() { object x = 0; } // local Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(8, 28), // (9,24): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // void F2(string x) { } // parameter Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(9, 24), // (10,26): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // void F3() { void x() { } } // method Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(10, 26), // (11,17): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // void F4<x>() { } // type parameter Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(11, 17), // (12,30): error CS1931: The range variable 'x' conflicts with a previous declaration of 'x' // void F5() { _ = from x in new[] { 1, 2, 3 } select x; } // range variable Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "x").WithArguments("x").WithLocation(12, 30)); comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void ShadowNames_Local_03() { var source = @"#pragma warning disable 0219 #pragma warning disable 8321 using System.Linq; class Program { static void M() { static void F1() { object x = 0; } // local static void F2(string x) { } // parameter static void F3() { void x() { } } // method static void F4<x>() { } // type parameter static void F5() { _ = from x in new[] { 1, 2, 3 } select x; } // range variable object x = null; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void ShadowNames_Parameter() { var source = @"#pragma warning disable 0219 #pragma warning disable 8321 using System.Linq; class Program { static void M(object x) { void F1() { object x = 0; } // local void F2(string x) { } // parameter void F3() { void x() { } } // method void F4<x>() { } // type parameter void F5() { _ = from x in new[] { 1, 2, 3 } select x; } // range variable } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3); // The conflict between the type parameter in F4<x>() and the parameter // in M(object x) is not reported, for backwards compatibility. comp.VerifyDiagnostics( // (8,28): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // void F1() { object x = 0; } // local Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(8, 28), // (9,24): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // void F2(string x) { } // parameter Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(9, 24), // (10,26): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // void F3() { void x() { } } // method Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(10, 26), // (12,30): error CS1931: The range variable 'x' conflicts with a previous declaration of 'x' // void F5() { _ = from x in new[] { 1, 2, 3 } select x; } // range variable Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "x").WithArguments("x").WithLocation(12, 30)); comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void ShadowNames_TypeParameter() { var source = @"#pragma warning disable 0219 #pragma warning disable 8321 using System.Linq; class Program { static void M<x>() { void F1() { object x = 0; } // local void F2(string x) { } // parameter void F3() { void x() { } } // method void F4<x>() { } // type parameter void F5() { _ = from x in new[] { 1, 2, 3 } select x; } // range variable } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics( // (8,28): error CS0412: 'x': a parameter, local variable, or local function cannot have the same name as a method type parameter // void F1() { object x = 0; } // local Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "x").WithArguments("x").WithLocation(8, 28), // (9,24): error CS0412: 'x': a parameter, local variable, or local function cannot have the same name as a method type parameter // void F2(string x) { } // parameter Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "x").WithArguments("x").WithLocation(9, 24), // (10,26): error CS0412: 'x': a parameter, local variable, or local function cannot have the same name as a method type parameter // void F3() { void x() { } } // method Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "x").WithArguments("x").WithLocation(10, 26), // (11,17): warning CS8387: Type parameter 'x' has the same name as the type parameter from outer method 'Program.M<x>()' // void F4<x>() { } // type parameter Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterMethodTypeParameter, "x").WithArguments("x", "Program.M<x>()").WithLocation(11, 17), // (12,30): error CS1948: The range variable 'x' cannot have the same name as a method type parameter // void F5() { _ = from x in new[] { 1, 2, 3 } select x; } // range variable Diagnostic(ErrorCode.ERR_QueryRangeVariableSameAsTypeParam, "x").WithArguments("x").WithLocation(12, 30)); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,17): warning CS8387: Type parameter 'x' has the same name as the type parameter from outer method 'Program.M<x>()' // void F4<x>() { } // type parameter Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterMethodTypeParameter, "x").WithArguments("x", "Program.M<x>()").WithLocation(11, 17)); } [Fact] public void ShadowNames_LocalFunction_01() { var source = @"#pragma warning disable 0219 #pragma warning disable 8321 using System.Linq; class Program { static void M() { void x() { } void F1() { object x = 0; } // local void F2(string x) { } // parameter void F3() { void x() { } } // method void F4<x>() { } // type parameter void F5() { _ = from x in new[] { 1, 2, 3 } select x; } // range variable } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics( // (9,28): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // void F1() { object x = 0; } // local Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(9, 28), // (10,24): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // void F2(string x) { } // parameter Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(10, 24), // (11,26): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // void F3() { void x() { } } // method Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(11, 26), // (12,17): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // void F4<x>() { } // type parameter Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(12, 17), // (13,30): error CS1931: The range variable 'x' conflicts with a previous declaration of 'x' // void F5() { _ = from x in new[] { 1, 2, 3 } select x; } // range variable Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "x").WithArguments("x").WithLocation(13, 30)); comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void ShadowNames_LocalFunction_02() { var source = @"#pragma warning disable 0219 #pragma warning disable 8321 class Program { static void M1() { void M1() { } } static void M2(object x) { void x() { } } static void M3() { object x = null; void x() { } } static void M4<T>() { void T() { } } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3); verifyDiagnostics(); comp = CreateCompilation(source); verifyDiagnostics(); void verifyDiagnostics() { comp.VerifyDiagnostics( // (11,14): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // void x() { } Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(11, 14), // (16,14): error CS0128: A local variable or function named 'x' is already defined in this scope // void x() { } Diagnostic(ErrorCode.ERR_LocalDuplicate, "x").WithArguments("x").WithLocation(16, 14), // (20,14): error CS0412: 'T': a parameter, local variable, or local function cannot have the same name as a method type parameter // void T() { } Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "T").WithArguments("T").WithLocation(20, 14)); } } [Fact] public void ShadowNames_ThisLocalFunction() { var source = @"#pragma warning disable 0219 #pragma warning disable 8321 using System.Linq; class Program { static void M() { void F1() { object F1 = 0; } // local void F2(string F2) { } // parameter void F3() { void F3() { } } // method void F4<F4>() { } // type parameter void F5() { _ = from F5 in new[] { 1, 2, 3 } select F5; } // range variable } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics( // (8,28): error CS0136: A local or parameter named 'F1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // void F1() { object F1 = 0; } // local Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "F1").WithArguments("F1").WithLocation(8, 28), // (9,24): error CS0136: A local or parameter named 'F2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // void F2(string F2) { } // parameter Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "F2").WithArguments("F2").WithLocation(9, 24), // (10,26): error CS0136: A local or parameter named 'F3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // void F3() { void F3() { } } // method Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "F3").WithArguments("F3").WithLocation(10, 26), // (11,17): error CS0136: A local or parameter named 'F4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // void F4<F4>() { } // type parameter Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "F4").WithArguments("F4").WithLocation(11, 17), // (12,30): error CS1931: The range variable 'F5' conflicts with a previous declaration of 'F5' // void F5() { _ = from F5 in new[] { 1, 2, 3 } select F5; } // range variable Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "F5").WithArguments("F5").WithLocation(12, 30)); comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void ShadowNames_LocalFunctionInsideLocalFunction_01() { var source = @"#pragma warning disable 0219 #pragma warning disable 8321 class Program { static void M<T>(object x) { void F() { void G1(int x) { } void G2() { int T = 0; } void G3<T>() { } } } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics( // (9,25): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // void G1(int x) { } Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(9, 25), // (10,29): error CS0412: 'T': a parameter, local variable, or local function cannot have the same name as a method type parameter // void G2() { int T = 0; } Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "T").WithArguments("T").WithLocation(10, 29), // (11,21): warning CS8387: Type parameter 'T' has the same name as the type parameter from outer method 'Program.M<T>(object)' // void G3<T>() { } Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterMethodTypeParameter, "T").WithArguments("T", "Program.M<T>(object)").WithLocation(11, 21)); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,21): warning CS8387: Type parameter 'T' has the same name as the type parameter from outer method 'Program.M<T>(object)' // void G3<T>() { } Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterMethodTypeParameter, "T").WithArguments("T", "Program.M<T>(object)").WithLocation(11, 21)); } [Fact] public void ShadowNames_LocalFunctionInsideLocalFunction_02() { var source = @"#pragma warning disable 0219 #pragma warning disable 8321 class Program { static void M<T>(object x) { static void F1() { void G1(int x) { } } void F2() { static void G2() { int T = 0; } } static void F3() { static void G3<T>() { } } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (17,28): warning CS8387: Type parameter 'T' has the same name as the type parameter from outer method 'Program.M<T>(object)' // static void G3<T>() { } Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterMethodTypeParameter, "T").WithArguments("T", "Program.M<T>(object)").WithLocation(17, 28)); } [Fact] public void ShadowNames_LocalFunctionInsideLambda_01() { var source = @"#pragma warning disable 0219 #pragma warning disable 8321 using System; class Program { static void M() { Action a1 = () => { int x = 0; void F1() { object x = null; } }; Action a2 = () => { int T = 0; void F2<T>() { } }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics( // (11,32): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // void F1() { object x = null; } Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(11, 32), // (16,21): error CS0136: A local or parameter named 'T' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // void F2<T>() { } Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "T").WithArguments("T").WithLocation(16, 21)); comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void ShadowNames_LocalFunctionInsideLambda_02() { var source = @"#pragma warning disable 0219 #pragma warning disable 8321 using System; class Program { static void M() { Action<int> a1 = x => { void F1(object x) { } }; Action<int> a2 = (int T) => { void F2<T>() { } }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3); // The conflict between the type parameter in F2<T>() and the parameter // in a2 is not reported, for backwards compatibility. comp.VerifyDiagnostics( // (10,28): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // void F1(object x) { } Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(10, 28)); comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void ShadowNames_LocalFunctionInsideLambda_03() { var source = @"using System; class Program { static void M() { Action<int> a = x => { void x() { } x(); }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3); // The conflict between the local function and the parameter is not reported, // for backwards compatibility. comp.VerifyDiagnostics(); comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void StaticWithThisReference() { var source = @"#pragma warning disable 8321 class C { void M() { static object F1() => this.GetHashCode(); static object F2() => base.GetHashCode(); static void F3() { object G3() => ToString(); } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,31): error CS8422: A static local function cannot contain a reference to 'this' or 'base'. // static object F1() => this.GetHashCode(); Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureThis, "this").WithLocation(6, 31), // (7,31): error CS8422: A static local function cannot contain a reference to 'this' or 'base'. // static object F2() => base.GetHashCode(); Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureThis, "base").WithLocation(7, 31), // (10,28): error CS8422: A static local function cannot contain a reference to 'this' or 'base'. // object G3() => ToString(); Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureThis, "ToString").WithLocation(10, 28)); } [Fact] public void StaticWithVariableReference() { var source = @"#pragma warning disable 8321 class C { static void M(object x) { object y = null; static object F1() => x; static object F2() => y; static void F3() { object G3() => x; } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,31): error CS8421: A static local function cannot contain a reference to 'x'. // static object F1() => x; Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "x").WithArguments("x").WithLocation(7, 31), // (8,31): error CS8421: A static local function cannot contain a reference to 'y'. // static object F2() => y; Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "y").WithArguments("y").WithLocation(8, 31), // (11,28): error CS8421: A static local function cannot contain a reference to 'x'. // object G3() => x; Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "x").WithArguments("x").WithLocation(11, 28)); } [Fact] public void StaticWithLocalFunctionVariableReference_01() { var source = @"#pragma warning disable 8321 class C { static void M() { static void F(object x) { object y = null; object G1() => x ?? y; static object G2() => x ?? y; } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,35): error CS8421: A static local function cannot contain a reference to 'x'. // static object G2() => x ?? y; Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "x").WithArguments("x").WithLocation(10, 35), // (10,40): error CS8421: A static local function cannot contain a reference to 'y'. // static object G2() => x ?? y; Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "y").WithArguments("y").WithLocation(10, 40)); } [Fact] public void StaticWithLocalFunctionVariableReference_02() { var source = @"#pragma warning disable 8321 class C { static void M(int x) { static void F1(int y) { int F2() => x + y; } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,25): error CS8421: A static local function cannot contain a reference to 'x'. // int F2() => x + y; Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "x").WithArguments("x").WithLocation(8, 25)); } /// <summary> /// Can reference type parameters from enclosing scope. /// </summary> [Fact] public void StaticWithTypeParameterReferences() { var source = @"using static System.Console; class A<T> { internal string F1() { static string L1() => typeof(T).FullName; return L1(); } } class B { internal string F2<T>() { static string L2() => typeof(T).FullName; return L2(); } internal static string F3() { static string L3<T>() { static string L4() => typeof(T).FullName; return L4(); } return L3<byte>(); } } class Program { static void Main() { WriteLine(new A<int>().F1()); WriteLine(new B().F2<string>()); WriteLine(B.F3()); } }"; CompileAndVerify(source, expectedOutput: @"System.Int32 System.String System.Byte"); } [Fact] public void Conditional_ThisReferenceInStatic() { var source = @"#pragma warning disable 0649 #pragma warning disable 8321 using System.Diagnostics; class A { internal object _f; } class B : A { [Conditional(""MyDefine"")] static void F(object o) { } void M() { static void F1() { F(this); } static void F2() { F(base._f); } static void F3() { F(_f); } } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular.WithPreprocessorSymbols("MyDefine")); verifyDiagnostics(); comp = CreateCompilation(source, parseOptions: TestOptions.Regular); verifyDiagnostics(); void verifyDiagnostics() { comp.VerifyDiagnostics( // (16,30): error CS8422: A static local function cannot contain a reference to 'this' or 'base'. // static void F1() { F(this); } Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureThis, "this").WithLocation(16, 30), // (17,30): error CS8422: A static local function cannot contain a reference to 'this' or 'base'. // static void F2() { F(base._f); } Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureThis, "base").WithLocation(17, 30), // (18,30): error CS8422: A static local function cannot contain a reference to 'this' or 'base'. // static void F3() { F(_f); } Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureThis, "_f").WithLocation(18, 30)); } } [Fact] public void LocalFunctionConditional_Errors() { var source = @" using System.Diagnostics; class C { void M() { #pragma warning disable 8321 // Unreferenced local function [Conditional(""DEBUG"")] // 1 int local1() => 42; [Conditional(""DEBUG"")] // 2 void local2(out int i) { i = 42; } } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (10,10): error CS0578: The Conditional attribute is not valid on 'local1()' because its return type is not void // [Conditional("DEBUG")] // 1 Diagnostic(ErrorCode.ERR_ConditionalMustReturnVoid, @"Conditional(""DEBUG"")").WithArguments("local1()").WithLocation(10, 10), // (13,10): error CS0685: Conditional member 'local2(out int)' cannot have an out parameter // [Conditional("DEBUG")] // 2 Diagnostic(ErrorCode.ERR_ConditionalWithOutParam, @"Conditional(""DEBUG"")").WithArguments("local2(out int)").WithLocation(13, 10)); } [Fact] public void LocalFunctionObsolete() { var source = @" using System; class C { void M1() { local1(); // 1 local2(); // 2 [Obsolete] void local1() { } [Obsolete(""hello"", true)] void local2() { } #pragma warning disable 8321 // Unreferenced local function [Obsolete] void local3() { // no diagnostics expected when calling an Obsolete method within an Obsolete method local1(); local2(); } } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,9): warning CS0612: 'local1()' is obsolete // local1(); // 1 Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "local1()").WithArguments("local1()").WithLocation(8, 9), // (9,9): error CS0619: 'local2()' is obsolete: 'hello' // local2(); // 2 Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "local2()").WithArguments("local2()", "hello").WithLocation(9, 9)); } [Fact] public void LocalFunction_AttributeMarkedObsolete() { var source = @" using System; [Obsolete] class Attr : Attribute { } class C { void M1() { #pragma warning disable 8321 [Attr] void local1() { } // 1 [return: Attr] void local2() { } // 2 void local3([Attr] int i) { } // 3 void local4<[Attr] T>(T t) { } // 4 } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (12,10): warning CS0612: 'Attr' is obsolete // [Attr] void local1() { } // 1 Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "Attr").WithArguments("Attr").WithLocation(12, 10), // (13,18): warning CS0612: 'Attr' is obsolete // [return: Attr] void local2() { } // 2 Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "Attr").WithArguments("Attr").WithLocation(13, 18), // (14,22): warning CS0612: 'Attr' is obsolete // void local3([Attr] int i) { } // 3 Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "Attr").WithArguments("Attr").WithLocation(14, 22), // (15,22): warning CS0612: 'Attr' is obsolete // void local4<[Attr] T>(T t) { } // 4 Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "Attr").WithArguments("Attr").WithLocation(15, 22)); } [Fact] public void LocalFunction_NotNullIfNotNullAttribute() { var source = @" using System.Diagnostics.CodeAnalysis; #nullable enable class C { void M() { _ = local1(null).ToString(); // 1 _ = local1(""hello"").ToString(); [return: NotNullIfNotNull(""s1"")] string? local1(string? s1) => s1; } } "; var comp = CreateCompilation(new[] { NotNullIfNotNullAttributeDefinition, source }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (10,13): warning CS8602: Dereference of a possibly null reference. // _ = local1(null).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "local1(null)").WithLocation(10, 13)); } [Fact] public void LocalFunction_MaybeNullWhenAttribute() { var source = @" #nullable enable using System.Diagnostics.CodeAnalysis; class C { void M() { _ = tryGetValue(true, out var s) ? s.ToString() : s.ToString(); // 1 bool tryGetValue(bool b, [MaybeNullWhen(false)] out string s1) { s1 = b ? ""abc"" : null; return b; } } } "; var comp = CreateCompilation(new[] { MaybeNullWhenAttributeDefinition, source }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (12,15): warning CS8602: Dereference of a possibly null reference. // : s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(12, 15)); } [Fact] public void LocalFunction_MaybeNullWhenAttribute_CheckUsage() { var source = @" #nullable enable using System.Diagnostics.CodeAnalysis; class C { void M() { var s = ""abc""; local1(); tryGetValue(""a"", out s); local1(); void local1() { _ = s.ToString(); // 1 } bool tryGetValue(string key, [MaybeNullWhen(false)] out string s1) { s1 = key; return true; } } } "; var comp = CreateCompilation(new[] { MaybeNullWhenAttributeDefinition, source }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (18,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(18, 17)); } [Fact] public void LocalFunction_AllowNullAttribute() { var source = @" #nullable enable using System.Diagnostics.CodeAnalysis; class C { void M<T>([AllowNull] T t1, T t2) { local1(t1); local1(t2); local2(t1); // 1 local2(t2); void local1([AllowNull] T t) { } void local2(T t) { } } } "; var comp = CreateCompilation(new[] { AllowNullAttributeDefinition, source }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (13,16): warning CS8604: Possible null reference argument for parameter 't' in 'void local2(T t)'. // local2(t1); // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t1").WithArguments("t", "void local2(T t)").WithLocation(13, 16)); } [Fact] public void LocalFunction_MaybeNullAttribute() { var source = @" #nullable enable using System.Diagnostics.CodeAnalysis; class C { void M<TOuter>() { getDefault<string>().ToString(); // 1 getDefault<string?>().ToString(); // 2 getDefault<int>().ToString(); getDefault<int?>().Value.ToString(); // 3 getDefault<TOuter>().ToString(); // 4 [return: MaybeNull] T getDefault<T>() => default(T); } } "; var comp = CreateCompilation(new[] { MaybeNullAttributeDefinition, source }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // getDefault<string>().ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "getDefault<string>()").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // getDefault<string?>().ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "getDefault<string?>()").WithLocation(11, 9), // (13,9): warning CS8629: Nullable value type may be null. // getDefault<int?>().Value.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "getDefault<int?>()").WithLocation(13, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // getDefault<TOuter>().ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "getDefault<TOuter>()").WithLocation(14, 9)); } [Fact] public void LocalFunction_Nullable_CheckUsage_DoesNotUsePostconditions() { var source = @" #nullable enable using System.Diagnostics.CodeAnalysis; class C { void M() { var s0 = ""hello""; local1(out s0); bool local1([MaybeNullWhen(false)] out string s1) { s0.ToString(); s1 = ""world""; return true; } } } "; var comp = CreateCompilation(new[] { MaybeNullWhenAttributeDefinition, source }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); } [Fact] public void LocalFunction_DoesNotReturn() { var source = @" #nullable enable using System.Diagnostics.CodeAnalysis; class C { void M(string? s) { local1(); s.ToString(); [DoesNotReturn] void local1() { throw null!; } } } "; var comp = CreateCompilation(new[] { DoesNotReturnAttributeDefinition, source }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); } [Fact] public void LocalFunction_DoesNotReturnIf() { var source = @" #nullable enable using System.Diagnostics.CodeAnalysis; class C { void M(string? s1, string? s2) { local1(s1 != null); s1.ToString(); local1(false); s2.ToString(); void local1([DoesNotReturnIf(false)] bool b) { throw null!; } } } "; var comp = CreateCompilation(new[] { DoesNotReturnIfAttributeDefinition, source }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); } [Fact] public void NameOf_ThisReferenceInStatic() { var source = @"#pragma warning disable 8321 class C { void M() { static object F1() => nameof(this.ToString); static object F2() => nameof(base.GetHashCode); static object F3() => nameof(M); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void NameOf_InstanceMemberInStatic() { var source = @"#pragma warning disable 0649 #pragma warning disable 8321 class C { object _f; static void M() { _ = nameof(_f); static object F() => nameof(_f); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = GetNameOfExpressions(tree)[1]; var symbol = model.GetSymbolInfo(expr).Symbol; Assert.Equal("System.Object C._f", symbol.ToTestDisplayString()); } [Fact] public void NameOf_CapturedVariableInStatic() { var source = @"#pragma warning disable 8321 class C { static void M(object x) { static object F() => nameof(x); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = GetNameOfExpressions(tree)[0]; var symbol = model.GetSymbolInfo(expr).Symbol; Assert.Equal("System.Object x", symbol.ToTestDisplayString()); } /// <summary> /// nameof(x) should bind to shadowing symbol. /// </summary> [Fact] public void NameOf_ShadowedVariable() { var source = @"#pragma warning disable 8321 class C { static void M(object x) { object F() { int x = 0; return nameof(x); } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = GetNameOfExpressions(tree)[0]; var symbol = model.GetSymbolInfo(expr).Symbol; Assert.Equal(SymbolKind.Local, symbol.Kind); Assert.Equal("System.Int32 x", symbol.ToTestDisplayString()); } /// <summary> /// nameof(T) should bind to shadowing symbol. /// </summary> [Fact] public void NameOf_ShadowedTypeParameter() { var source = @"#pragma warning disable 8321 class C { static void M<T>() { object F1() { int T = 0; return nameof(T); } object F2<T>() { return nameof(T); } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,19): warning CS8387: Type parameter 'T' has the same name as the type parameter from outer method 'C.M<T>()' // object F2<T>() Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterMethodTypeParameter, "T").WithArguments("T", "C.M<T>()").WithLocation(11, 19)); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var exprs = GetNameOfExpressions(tree); var symbol = model.GetSymbolInfo(exprs[0]).Symbol; Assert.Equal(SymbolKind.Local, symbol.Kind); Assert.Equal("System.Int32 T", symbol.ToTestDisplayString()); symbol = model.GetSymbolInfo(exprs[1]).Symbol; Assert.Equal(SymbolKind.TypeParameter, symbol.Kind); Assert.Equal("System.Object F2<T>()", symbol.ContainingSymbol.ToTestDisplayString()); } /// <summary> /// typeof(T) should bind to nearest type. /// </summary> [Fact] public void TypeOf_ShadowedTypeParameter() { var source = @"#pragma warning disable 0219 #pragma warning disable 8321 class C { static void M<T>() { object F1() { int T = 0; return typeof(T); } object F2<T>() { return typeof(T); } object F3<U>() { return typeof(U); } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (12,19): warning CS8387: Type parameter 'T' has the same name as the type parameter from outer method 'C.M<T>()' // object F2<T>() Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterMethodTypeParameter, "T").WithArguments("T", "C.M<T>()").WithLocation(12, 19)); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var exprs = tree.GetRoot().DescendantNodes().OfType<TypeOfExpressionSyntax>().Select(n => n.Type).ToImmutableArray(); var symbol = model.GetSymbolInfo(exprs[0]).Symbol; Assert.Equal(SymbolKind.TypeParameter, symbol.Kind); Assert.Equal("void C.M<T>()", symbol.ContainingSymbol.ToTestDisplayString()); symbol = model.GetSymbolInfo(exprs[1]).Symbol; Assert.Equal(SymbolKind.TypeParameter, symbol.Kind); Assert.Equal("System.Object F2<T>()", symbol.ContainingSymbol.ToTestDisplayString()); symbol = model.GetSymbolInfo(exprs[2]).Symbol; Assert.Equal(SymbolKind.TypeParameter, symbol.Kind); Assert.Equal("System.Object F3<U>()", symbol.ContainingSymbol.ToTestDisplayString()); } /// <summary> /// sizeof(T) should bind to nearest type. /// </summary> [Fact] public void SizeOf_ShadowedTypeParameter() { var source = @"#pragma warning disable 0219 #pragma warning disable 8321 unsafe class C { static void M<T>() where T : unmanaged { object F1() { int T = 0; return sizeof(T); } object F2<T>() where T : unmanaged { return sizeof(T); } object F3<U>() where U : unmanaged { return sizeof(U); } } }"; var comp = CreateCompilation(source, options: TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (12,19): warning CS8387: Type parameter 'T' has the same name as the type parameter from outer method 'C.M<T>()' // object F2<T>() Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterMethodTypeParameter, "T").WithArguments("T", "C.M<T>()").WithLocation(12, 19)); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var exprs = tree.GetRoot().DescendantNodes().OfType<SizeOfExpressionSyntax>().Select(n => n.Type).ToImmutableArray(); var symbol = model.GetSymbolInfo(exprs[0]).Symbol; Assert.Equal(SymbolKind.TypeParameter, symbol.Kind); Assert.Equal("void C.M<T>()", symbol.ContainingSymbol.ToTestDisplayString()); symbol = model.GetSymbolInfo(exprs[1]).Symbol; Assert.Equal(SymbolKind.TypeParameter, symbol.Kind); Assert.Equal("System.Object F2<T>()", symbol.ContainingSymbol.ToTestDisplayString()); symbol = model.GetSymbolInfo(exprs[2]).Symbol; Assert.Equal(SymbolKind.TypeParameter, symbol.Kind); Assert.Equal("System.Object F3<U>()", symbol.ContainingSymbol.ToTestDisplayString()); } private static ImmutableArray<ExpressionSyntax> GetNameOfExpressions(SyntaxTree tree) { return tree.GetRoot().DescendantNodes(). OfType<InvocationExpressionSyntax>(). Where(n => n.Expression.ToString() == "nameof"). Select(n => n.ArgumentList.Arguments[0].Expression). ToImmutableArray(); } [Fact] public void ShadowWithSelfReferencingLocal() { var source = @"using System; class Program { static void Main() { int x = 13; void Local() { int x = (x = 0) + 42; Console.WriteLine(x); } Local(); Console.WriteLine(x); } }"; CompileAndVerify(source, expectedOutput: @"42 13"); } [Fact, WorkItem(38129, "https://github.com/dotnet/roslyn/issues/38129")] public void StaticLocalFunctionLocalFunctionReference_01() { var source = @"#pragma warning disable 8321 class C { static void M() { void F1() {} static void F2() {} static void F3() { F1(); F2(); } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,13): error CS8421: A static local function cannot contain a reference to 'F1'. // F1(); Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "F1()").WithArguments("F1").WithLocation(11, 13)); } [Fact, WorkItem(39706, "https://github.com/dotnet/roslyn/issues/39706")] public void StaticLocalFunctionLocalFunctionReference_02() { var source = @"#pragma warning disable 8321 class Program { static void Method() { void Local<T>() {} static void StaticLocal() { Local<int>(); } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,13): error CS8421: A static local function cannot contain a reference to 'Local'. // Local<int>(); Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "Local<int>()").WithArguments("Local").WithLocation(9, 13)); } [Fact, WorkItem(39706, "https://github.com/dotnet/roslyn/issues/39706")] public void StaticLocalFunctionLocalFunctionReference_03() { var source = @"using System; class Program { static void Method() { int i = 0; void Local<T>() { i = 0; } Action a = () => i++; static void StaticLocal() { Local<int>(); } StaticLocal(); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (14,13): error CS8421: A static local function cannot contain a reference to 'Local'. // Local<int>(); Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "Local<int>()").WithArguments("Local").WithLocation(14, 13)); } [Fact, WorkItem(38240, "https://github.com/dotnet/roslyn/issues/38240")] public void StaticLocalFunctionLocalFunctionDelegateReference_01() { var source = @"#pragma warning disable 8321 using System; class C { static void M() { void F1() {} static void F2() { Action a = F1; _ = new Action(F1); } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,24): error CS8421: A static local function cannot contain a reference to 'F1'. // Action a = F1; Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "F1").WithArguments("F1").WithLocation(11, 24), // (12,28): error CS8421: A static local function cannot contain a reference to 'F1'. // _ = new Action(F1); Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "F1").WithArguments("F1").WithLocation(12, 28)); } [Fact, WorkItem(39706, "https://github.com/dotnet/roslyn/issues/39706")] public void StaticLocalFunctionLocalFunctionDelegateReference_02() { var source = @"#pragma warning disable 8321 using System; class Program { static void Method() { void Local<T>() {} static void StaticLocal() { Action a; a = Local<int>; a = new Action(Local<string>); } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,17): error CS8421: A static local function cannot contain a reference to 'Local'. // a = Local<int>; Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "Local<int>").WithArguments("Local").WithLocation(11, 17), // (12,28): error CS8421: A static local function cannot contain a reference to 'Local'. // a = new Action(Local<string>); Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "Local<string>").WithArguments("Local").WithLocation(12, 28)); } [Fact, WorkItem(39706, "https://github.com/dotnet/roslyn/issues/39706")] public void StaticLocalFunctionLocalFunctionDelegateReference_03() { var source = @"using System; class Program { static void Method() { int i = 0; void Local<T>() { i = 0; } Action a = () => i++; a = StaticLocal(); static Action StaticLocal() { return Local<int>; } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (15,20): error CS8421: A static local function cannot contain a reference to 'Local'. // return Local<int>; Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "Local<int>").WithArguments("Local").WithLocation(15, 20)); } [Fact] public void StaticLocalFunctionGenericStaticLocalFunction() { var source = @"using System; class Program { static void Main() { static void F1<T>() { Console.WriteLine(typeof(T)); } static void F2() { F1<int>(); Action a = F1<string>; a(); } F2(); } }"; CompileAndVerify(source, expectedOutput: @"System.Int32 System.String"); } [Fact, WorkItem(38240, "https://github.com/dotnet/roslyn/issues/38240")] public void StaticLocalFunctionStaticFunctionsDelegateReference() { var source = @"#pragma warning disable 8321 using System; class C { static void M() { static void F1() {} static void F2() { Action m = M; Action f1 = F1; _ = new Action(M); _ = new Action(F1); } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact, WorkItem(38240, "https://github.com/dotnet/roslyn/issues/38240")] public void StaticLocalFunctionThisAndBaseDelegateReference() { var source = @"#pragma warning disable 8321 using System; class B { public virtual void M() {} } class C : B { public override void M() { static void F() { Action a1 = base.M; Action a2 = this.M; Action a3 = M; _ = new Action(base.M); _ = new Action(this.M); _ = new Action(M); } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (14,25): error CS8422: A static local function cannot contain a reference to 'this' or 'base'. // Action a1 = base.M; Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureThis, "base").WithLocation(14, 25), // (15,25): error CS8422: A static local function cannot contain a reference to 'this' or 'base'. // Action a2 = this.M; Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureThis, "this").WithLocation(15, 25), // (16,25): error CS8422: A static local function cannot contain a reference to 'this' or 'base'. // Action a3 = M; Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureThis, "M").WithLocation(16, 25), // (17,28): error CS8422: A static local function cannot contain a reference to 'this' or 'base'. // _ = new Action(base.M); Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureThis, "base").WithLocation(17, 28), // (18,28): error CS8422: A static local function cannot contain a reference to 'this' or 'base'. // _ = new Action(this.M); Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureThis, "this").WithLocation(18, 28), // (19,28): error CS8422: A static local function cannot contain a reference to 'this' or 'base'. // _ = new Action(M); Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureThis, "M").WithLocation(19, 28)); } [Fact, WorkItem(38240, "https://github.com/dotnet/roslyn/issues/38240")] public void StaticLocalFunctionDelegateReferenceWithReceiver() { var source = @"#pragma warning disable 649 #pragma warning disable 8321 using System; class C { object f; void M() { object l; static void F1() { _ = new Func<int>(f.GetHashCode); _ = new Func<int>(l.GetHashCode); } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (14,31): error CS8422: A static local function cannot contain a reference to 'this' or 'base'. // _ = new Func<int>(f.GetHashCode); Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureThis, "f").WithLocation(14, 31), // (15,31): error CS8421: A static local function cannot contain a reference to 'l'. // _ = new Func<int>(l.GetHashCode); Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "l").WithArguments("l").WithLocation(15, 31)); } [Fact] [WorkItem(38143, "https://github.com/dotnet/roslyn/issues/38143")] public void EmittedAsStatic_01() { var source = @"class Program { static void M() { static void local() { } System.Action action = local; } }"; CompileAndVerify(source, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: m => { var method = (MethodSymbol)m.GlobalNamespace.GetMember("Program.<M>g__local|0_0"); Assert.True(method.IsStatic); }); } [Fact] [WorkItem(38143, "https://github.com/dotnet/roslyn/issues/38143")] public void EmittedAsStatic_02() { var source = @"class Program { static void M<T>() { static void local(T t) { System.Console.Write(t.GetType().FullName); } System.Action<T> action = local; action(default(T)); } static void Main() { M<int>(); } }"; CompileAndVerify(source, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), expectedOutput: "System.Int32", symbolValidator: m => { var method = (MethodSymbol)m.GlobalNamespace.GetMember("Program.<M>g__local|0_0"); Assert.True(method.IsStatic); Assert.True(method.IsGenericMethod); Assert.Equal("void Program.<M>g__local|0_0<T>(T t)", method.ToTestDisplayString()); }); } /// <summary> /// Local function in generic method is emitted as a generic /// method even if no references to type parameters. /// </summary> [Fact] [WorkItem(38143, "https://github.com/dotnet/roslyn/issues/38143")] public void EmittedAsStatic_03() { var source = @"class Program { static void M<T>() where T : new() { static void local(object o) { System.Console.Write(o.GetType().FullName); } local(new T()); } static void Main() { M<int>(); } }"; CompileAndVerify(source, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), expectedOutput: "System.Int32", symbolValidator: m => { var method = (MethodSymbol)m.GlobalNamespace.GetMember("Program.<M>g__local|0_0"); Assert.True(method.IsStatic); Assert.True(method.IsGenericMethod); Assert.Equal("void Program.<M>g__local|0_0<T>(System.Object o)", method.ToTestDisplayString()); }); } /// <summary> /// Emit 'call' rather than 'callvirt' for local functions regardless of whether /// the local function is static. /// </summary> [Fact] public void EmitCallInstruction() { var source = @"using static System.Console; class Program { static void Main() { int i; void L1() => WriteLine(i++); static void L2(int i) => WriteLine(i); i = 1; L1(); L2(i); } }"; var verifier = CompileAndVerify(source, expectedOutput: @"1 2"); verifier.VerifyIL("Program.Main", @"{ // Code size 27 (0x1b) .maxstack 2 .locals init (Program.<>c__DisplayClass0_0 V_0) //CS$<>8__locals0 IL_0000: ldloca.s V_0 IL_0002: ldc.i4.1 IL_0003: stfld ""int Program.<>c__DisplayClass0_0.i"" IL_0008: ldloca.s V_0 IL_000a: call ""void Program.<Main>g__L1|0_0(ref Program.<>c__DisplayClass0_0)"" IL_000f: ldloc.0 IL_0010: ldfld ""int Program.<>c__DisplayClass0_0.i"" IL_0015: call ""void Program.<Main>g__L2|0_1(int)"" IL_001a: ret }"); } /// <summary> /// '_' should bind to '_' symbol in outer scope even in static local function. /// </summary> [Fact] public void UnderscoreInOuterScope() { var source = @"#pragma warning disable 8321 class C1 { object _; void F1() { void A1(object x) => _ = x; static void B1(object y) => _ = y; } } class C2 { static void F2() { object _; void A2(object x) => _ = x; static void B2(object y) => _ = y; } static void F3() { void A3(object x) => _ = x; static void B3(object y) => _ = y; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,37): error CS8422: A static local function cannot contain a reference to 'this' or 'base'. // static void B1(object y) => _ = y; Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureThis, "_").WithLocation(8, 37), // (17,37): error CS8421: A static local function cannot contain a reference to '_'. // static void B2(object y) => _ = y; Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "_").WithArguments("_").WithLocation(17, 37)); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var nodes = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>(); var actualSymbols = nodes.Select(n => model.GetSymbolInfo(n.Left).Symbol).Select(s => $"{s.Kind}: {s.ToTestDisplayString()}").ToArray(); var expectedSymbols = new[] { "Field: System.Object C1._", "Field: System.Object C1._", "Local: System.Object _", "Local: System.Object _", "Discard: System.Object _", "Discard: System.Object _", }; AssertEx.Equal(expectedSymbols, actualSymbols); } /// <summary> /// 'var' should bind to 'var' symbol in outer scope even in static local function. /// </summary> [Fact] public void VarInOuterScope() { var source = @"#pragma warning disable 8321 class C1 { class var { } static void F1() { void A1(object x) { var y = x; } static void B1(object x) { var y = x; } } } namespace N { using var = System.String; class C2 { static void F2() { void A2(object x) { var y = x; } static void B3(object x) { var y = x; } } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,37): error CS0266: Cannot implicitly convert type 'object' to 'C1.var'. An explicit conversion exists (are you missing a cast?) // void A1(object x) { var y = x; } Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x").WithArguments("object", "C1.var").WithLocation(7, 37), // (8,44): error CS0266: Cannot implicitly convert type 'object' to 'C1.var'. An explicit conversion exists (are you missing a cast?) // static void B1(object x) { var y = x; } Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x").WithArguments("object", "C1.var").WithLocation(8, 44), // (18,41): error CS0266: Cannot implicitly convert type 'object' to 'string'. An explicit conversion exists (are you missing a cast?) // void A2(object x) { var y = x; } Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x").WithArguments("object", "string").WithLocation(18, 41), // (19,48): error CS0266: Cannot implicitly convert type 'object' to 'string'. An explicit conversion exists (are you missing a cast?) // static void B3(object x) { var y = x; } Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x").WithArguments("object", "string").WithLocation(19, 48)); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var nodes = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>(); var actualSymbols = nodes.Select(n => model.GetDeclaredSymbol(n)).ToTestDisplayStrings(); var expectedSymbols = new[] { "C1.var y", "C1.var y", "System.String y", "System.String y", }; AssertEx.Equal(expectedSymbols, actualSymbols); } [Fact] public void AwaitWithinAsyncOuterScope_01() { var source = @"#pragma warning disable 1998 #pragma warning disable 8321 using System.Threading.Tasks; class Program { void F1() { void A1() { await Task.Yield(); } static void B1() { await Task.Yield(); } } void F2() { async void A2() { await Task.Yield(); } async static void B2() { await Task.Yield(); } } async void F3() { void A3() { await Task.Yield(); } static void B3() { await Task.Yield(); } } async void F4() { async void A4() { await Task.Yield(); } async static void B4() { await Task.Yield(); } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,21): error CS4033: The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'. // void A1() { await Task.Yield(); } Diagnostic(ErrorCode.ERR_BadAwaitWithoutVoidAsyncMethod, "await Task.Yield()").WithLocation(8, 21), // (9,28): error CS4033: The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'. // static void B1() { await Task.Yield(); } Diagnostic(ErrorCode.ERR_BadAwaitWithoutVoidAsyncMethod, "await Task.Yield()").WithLocation(9, 28), // (18,21): error CS4033: The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'. // void A3() { await Task.Yield(); } Diagnostic(ErrorCode.ERR_BadAwaitWithoutVoidAsyncMethod, "await Task.Yield()").WithLocation(18, 21), // (19,28): error CS4033: The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'. // static void B3() { await Task.Yield(); } Diagnostic(ErrorCode.ERR_BadAwaitWithoutVoidAsyncMethod, "await Task.Yield()").WithLocation(19, 28)); } /// <summary> /// 'await' should be a contextual keyword in the same way, /// regardless of whether local function is static. /// </summary> [Fact] public void AwaitWithinAsyncOuterScope_02() { var source = @"#pragma warning disable 1998 #pragma warning disable 8321 class Program { void F1() { void A1<await>() { } static void B1<await>() { } } void F2() { async void A2<await>() { } async static void B2<await>() { } } async void F3() { void A3<await>() { } static void B3<await>() { } } async void F4() { async void A4<await>() { } async static void B4<await>() { } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (12,23): error CS4003: 'await' cannot be used as an identifier within an async method or lambda expression // async void A2<await>() { } Diagnostic(ErrorCode.ERR_BadAwaitAsIdentifier, "await").WithLocation(12, 23), // (13,30): error CS4003: 'await' cannot be used as an identifier within an async method or lambda expression // async static void B2<await>() { } Diagnostic(ErrorCode.ERR_BadAwaitAsIdentifier, "await").WithLocation(13, 30), // (22,23): error CS4003: 'await' cannot be used as an identifier within an async method or lambda expression // async void A4<await>() { } Diagnostic(ErrorCode.ERR_BadAwaitAsIdentifier, "await").WithLocation(22, 23), // (23,30): error CS4003: 'await' cannot be used as an identifier within an async method or lambda expression // async static void B4<await>() { } Diagnostic(ErrorCode.ERR_BadAwaitAsIdentifier, "await").WithLocation(23, 30)); } } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/Workspaces/Core/Portable/SymbolKey/SymbolKey.FunctionPointerTypeSymbolKey.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Reflection.Metadata; namespace Microsoft.CodeAnalysis { internal partial struct SymbolKey { private static class FunctionPointerTypeSymbolKey { public static void Create(IFunctionPointerTypeSymbol symbol, SymbolKeyWriter visitor) { var callingConvention = symbol.Signature.CallingConvention; visitor.WriteInteger((int)callingConvention); if (callingConvention == SignatureCallingConvention.Unmanaged) { visitor.WriteSymbolKeyArray(symbol.Signature.UnmanagedCallingConventionTypes); } visitor.WriteRefKind(symbol.Signature.RefKind); visitor.WriteSymbolKey(symbol.Signature.ReturnType); visitor.WriteRefKindArray(symbol.Signature.Parameters); visitor.WriteParameterTypesArray(symbol.Signature.Parameters); } public static SymbolKeyResolution Resolve(SymbolKeyReader reader, out string? failureReason) { var callingConvention = (SignatureCallingConvention)reader.ReadInteger(); var callingConventionModifiers = ImmutableArray<INamedTypeSymbol>.Empty; if (callingConvention == SignatureCallingConvention.Unmanaged) { using var modifiersBuilder = reader.ReadSymbolKeyArray<INamedTypeSymbol>(out var conventionTypesFailureReason); if (conventionTypesFailureReason != null) { failureReason = $"({nameof(FunctionPointerTypeSymbolKey)} {nameof(callingConventionModifiers)} failed -> {conventionTypesFailureReason})"; return default; } callingConventionModifiers = modifiersBuilder.ToImmutable(); } var returnRefKind = reader.ReadRefKind(); var returnType = reader.ReadSymbolKey(out var returnTypeFailureReason); using var paramRefKinds = reader.ReadRefKindArray(); using var parameterTypes = reader.ReadSymbolKeyArray<ITypeSymbol>(out var parameterTypesFailureReason); if (returnTypeFailureReason != null) { failureReason = $"({nameof(FunctionPointerTypeSymbolKey)} {nameof(returnType)} failed -> {returnTypeFailureReason})"; return default; } if (parameterTypesFailureReason != null) { failureReason = $"({nameof(FunctionPointerTypeSymbolKey)} {nameof(parameterTypes)} failed -> {parameterTypesFailureReason})"; return default; } if (parameterTypes.IsDefault) { failureReason = $"({nameof(FunctionPointerTypeSymbolKey)} no parameter types)"; return default; } if (returnType.GetAnySymbol() is not ITypeSymbol returnTypeSymbol) { failureReason = $"({nameof(FunctionPointerTypeSymbolKey)} no return type)"; return default; } if (reader.Compilation.Language == LanguageNames.VisualBasic) { failureReason = $"({nameof(FunctionPointerTypeSymbolKey)} is not supported in {LanguageNames.VisualBasic})"; return default; } failureReason = null; return new SymbolKeyResolution(reader.Compilation.CreateFunctionPointerTypeSymbol( returnTypeSymbol, returnRefKind, parameterTypes.ToImmutable(), paramRefKinds.ToImmutable(), callingConvention, callingConventionModifiers)); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Reflection.Metadata; namespace Microsoft.CodeAnalysis { internal partial struct SymbolKey { private static class FunctionPointerTypeSymbolKey { public static void Create(IFunctionPointerTypeSymbol symbol, SymbolKeyWriter visitor) { var callingConvention = symbol.Signature.CallingConvention; visitor.WriteInteger((int)callingConvention); if (callingConvention == SignatureCallingConvention.Unmanaged) { visitor.WriteSymbolKeyArray(symbol.Signature.UnmanagedCallingConventionTypes); } visitor.WriteRefKind(symbol.Signature.RefKind); visitor.WriteSymbolKey(symbol.Signature.ReturnType); visitor.WriteRefKindArray(symbol.Signature.Parameters); visitor.WriteParameterTypesArray(symbol.Signature.Parameters); } public static SymbolKeyResolution Resolve(SymbolKeyReader reader, out string? failureReason) { var callingConvention = (SignatureCallingConvention)reader.ReadInteger(); var callingConventionModifiers = ImmutableArray<INamedTypeSymbol>.Empty; if (callingConvention == SignatureCallingConvention.Unmanaged) { using var modifiersBuilder = reader.ReadSymbolKeyArray<INamedTypeSymbol>(out var conventionTypesFailureReason); if (conventionTypesFailureReason != null) { failureReason = $"({nameof(FunctionPointerTypeSymbolKey)} {nameof(callingConventionModifiers)} failed -> {conventionTypesFailureReason})"; return default; } callingConventionModifiers = modifiersBuilder.ToImmutable(); } var returnRefKind = reader.ReadRefKind(); var returnType = reader.ReadSymbolKey(out var returnTypeFailureReason); using var paramRefKinds = reader.ReadRefKindArray(); using var parameterTypes = reader.ReadSymbolKeyArray<ITypeSymbol>(out var parameterTypesFailureReason); if (returnTypeFailureReason != null) { failureReason = $"({nameof(FunctionPointerTypeSymbolKey)} {nameof(returnType)} failed -> {returnTypeFailureReason})"; return default; } if (parameterTypesFailureReason != null) { failureReason = $"({nameof(FunctionPointerTypeSymbolKey)} {nameof(parameterTypes)} failed -> {parameterTypesFailureReason})"; return default; } if (parameterTypes.IsDefault) { failureReason = $"({nameof(FunctionPointerTypeSymbolKey)} no parameter types)"; return default; } if (returnType.GetAnySymbol() is not ITypeSymbol returnTypeSymbol) { failureReason = $"({nameof(FunctionPointerTypeSymbolKey)} no return type)"; return default; } if (reader.Compilation.Language == LanguageNames.VisualBasic) { failureReason = $"({nameof(FunctionPointerTypeSymbolKey)} is not supported in {LanguageNames.VisualBasic})"; return default; } failureReason = null; return new SymbolKeyResolution(reader.Compilation.CreateFunctionPointerTypeSymbol( returnTypeSymbol, returnRefKind, parameterTypes.ToImmutable(), paramRefKinds.ToImmutable(), callingConvention, callingConventionModifiers)); } } } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/EditorFeatures/Core/ExternalAccess/VSTypeScript/VSTypeScriptFindUsagesService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.FindUsages; using Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api; using Microsoft.CodeAnalysis.FindUsages; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Utilities; namespace Microsoft.CodeAnalysis.Editor.ExternalAccess.VSTypeScript { [ExportLanguageService(typeof(IFindUsagesService), InternalLanguageNames.TypeScript), Shared] internal class VSTypeScriptFindUsagesService : IFindUsagesService { private readonly IVSTypeScriptFindUsagesService _underlyingService; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VSTypeScriptFindUsagesService(IVSTypeScriptFindUsagesService underlyingService) { _underlyingService = underlyingService; } public Task FindReferencesAsync(Document document, int position, IFindUsagesContext context, CancellationToken cancellationToken) => _underlyingService.FindReferencesAsync(document, position, new VSTypeScriptFindUsagesContext(context), cancellationToken); public Task FindImplementationsAsync(Document document, int position, IFindUsagesContext context, CancellationToken cancellationToken) => _underlyingService.FindImplementationsAsync(document, position, new VSTypeScriptFindUsagesContext(context), cancellationToken); private class VSTypeScriptFindUsagesContext : IVSTypeScriptFindUsagesContext { private readonly IFindUsagesContext _context; private readonly Dictionary<VSTypeScriptDefinitionItem, DefinitionItem> _definitionItemMap = new(); public VSTypeScriptFindUsagesContext(IFindUsagesContext context) { _context = context; } public IVSTypeScriptStreamingProgressTracker ProgressTracker => new VSTypeScriptStreamingProgressTracker(_context.ProgressTracker); public ValueTask ReportMessageAsync(string message, CancellationToken cancellationToken) => _context.ReportMessageAsync(message, cancellationToken); public ValueTask SetSearchTitleAsync(string title, CancellationToken cancellationToken) => _context.SetSearchTitleAsync(title, cancellationToken); private DefinitionItem GetOrCreateDefinitionItem(VSTypeScriptDefinitionItem item) { lock (_definitionItemMap) { if (!_definitionItemMap.TryGetValue(item, out var result)) { result = DefinitionItem.Create( item.Tags, item.DisplayParts, item.SourceSpans, item.NameDisplayParts, item.Properties, item.DisplayableProperties, item.DisplayIfNoReferences); _definitionItemMap.Add(item, result); } return result; } } public ValueTask OnDefinitionFoundAsync(VSTypeScriptDefinitionItem definition, CancellationToken cancellationToken) { var item = GetOrCreateDefinitionItem(definition); return _context.OnDefinitionFoundAsync(item, cancellationToken); } public ValueTask OnReferenceFoundAsync(VSTypeScriptSourceReferenceItem reference, CancellationToken cancellationToken) { var item = GetOrCreateDefinitionItem(reference.Definition); return _context.OnReferenceFoundAsync(new SourceReferenceItem(item, reference.SourceSpan, reference.SymbolUsageInfo), cancellationToken); } } private class VSTypeScriptStreamingProgressTracker : IVSTypeScriptStreamingProgressTracker { private readonly IStreamingProgressTracker _progressTracker; public VSTypeScriptStreamingProgressTracker(IStreamingProgressTracker progressTracker) { _progressTracker = progressTracker; } public ValueTask AddItemsAsync(int count, CancellationToken cancellationToken) => _progressTracker.AddItemsAsync(count, cancellationToken); public ValueTask ItemCompletedAsync(CancellationToken cancellationToken) => _progressTracker.ItemCompletedAsync(cancellationToken); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.FindUsages; using Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api; using Microsoft.CodeAnalysis.FindUsages; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Utilities; namespace Microsoft.CodeAnalysis.Editor.ExternalAccess.VSTypeScript { [ExportLanguageService(typeof(IFindUsagesService), InternalLanguageNames.TypeScript), Shared] internal class VSTypeScriptFindUsagesService : IFindUsagesService { private readonly IVSTypeScriptFindUsagesService _underlyingService; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VSTypeScriptFindUsagesService(IVSTypeScriptFindUsagesService underlyingService) { _underlyingService = underlyingService; } public Task FindReferencesAsync(Document document, int position, IFindUsagesContext context, CancellationToken cancellationToken) => _underlyingService.FindReferencesAsync(document, position, new VSTypeScriptFindUsagesContext(context), cancellationToken); public Task FindImplementationsAsync(Document document, int position, IFindUsagesContext context, CancellationToken cancellationToken) => _underlyingService.FindImplementationsAsync(document, position, new VSTypeScriptFindUsagesContext(context), cancellationToken); private class VSTypeScriptFindUsagesContext : IVSTypeScriptFindUsagesContext { private readonly IFindUsagesContext _context; private readonly Dictionary<VSTypeScriptDefinitionItem, DefinitionItem> _definitionItemMap = new(); public VSTypeScriptFindUsagesContext(IFindUsagesContext context) { _context = context; } public IVSTypeScriptStreamingProgressTracker ProgressTracker => new VSTypeScriptStreamingProgressTracker(_context.ProgressTracker); public ValueTask ReportMessageAsync(string message, CancellationToken cancellationToken) => _context.ReportMessageAsync(message, cancellationToken); public ValueTask SetSearchTitleAsync(string title, CancellationToken cancellationToken) => _context.SetSearchTitleAsync(title, cancellationToken); private DefinitionItem GetOrCreateDefinitionItem(VSTypeScriptDefinitionItem item) { lock (_definitionItemMap) { if (!_definitionItemMap.TryGetValue(item, out var result)) { result = DefinitionItem.Create( item.Tags, item.DisplayParts, item.SourceSpans, item.NameDisplayParts, item.Properties, item.DisplayableProperties, item.DisplayIfNoReferences); _definitionItemMap.Add(item, result); } return result; } } public ValueTask OnDefinitionFoundAsync(VSTypeScriptDefinitionItem definition, CancellationToken cancellationToken) { var item = GetOrCreateDefinitionItem(definition); return _context.OnDefinitionFoundAsync(item, cancellationToken); } public ValueTask OnReferenceFoundAsync(VSTypeScriptSourceReferenceItem reference, CancellationToken cancellationToken) { var item = GetOrCreateDefinitionItem(reference.Definition); return _context.OnReferenceFoundAsync(new SourceReferenceItem(item, reference.SourceSpan, reference.SymbolUsageInfo), cancellationToken); } } private class VSTypeScriptStreamingProgressTracker : IVSTypeScriptStreamingProgressTracker { private readonly IStreamingProgressTracker _progressTracker; public VSTypeScriptStreamingProgressTracker(IStreamingProgressTracker progressTracker) { _progressTracker = progressTracker; } public ValueTask AddItemsAsync(int count, CancellationToken cancellationToken) => _progressTracker.AddItemsAsync(count, cancellationToken); public ValueTask ItemCompletedAsync(CancellationToken cancellationToken) => _progressTracker.ItemCompletedAsync(cancellationToken); } } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/Workspaces/Core/Portable/Shared/Extensions/ProjectExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Linq; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static partial class ProjectExtensions { public static bool IsFromPrimaryBranch(this Project project) => project.Solution.BranchId == project.Solution.Workspace.PrimaryBranchId; internal static Project WithSolutionOptions(this Project project, OptionSet options) => project.Solution.WithOptions(options).GetProject(project.Id)!; public static TextDocument? GetTextDocument(this Project project, DocumentId? documentId) => project.Solution.GetTextDocument(documentId); internal static DocumentId? GetDocumentForExternalLocation(this Project project, Location location) { Debug.Assert(location.Kind == LocationKind.ExternalFile); return project.GetDocumentIdWithFilePath(location.GetLineSpan().Path); } internal static DocumentId? GetDocumentForFile(this Project project, AdditionalText additionalText) => project.GetDocumentIdWithFilePath(additionalText.Path); private static DocumentId? GetDocumentIdWithFilePath(this Project project, string filePath) => project.Solution.GetDocumentIdsWithFilePath(filePath).FirstOrDefault(id => id.ProjectId == project.Id); public static Document GetRequiredDocument(this Project project, DocumentId documentId) { var document = project.GetDocument(documentId); if (document == null) { throw new InvalidOperationException(WorkspaceExtensionsResources.The_solution_does_not_contain_the_specified_document); } return document; } public static TextDocument GetRequiredTextDocument(this Project project, DocumentId documentId) { var document = project.GetTextDocument(documentId); if (document == null) { throw new InvalidOperationException(WorkspaceExtensionsResources.The_solution_does_not_contain_the_specified_document); } return document; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Linq; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static partial class ProjectExtensions { public static bool IsFromPrimaryBranch(this Project project) => project.Solution.BranchId == project.Solution.Workspace.PrimaryBranchId; internal static Project WithSolutionOptions(this Project project, OptionSet options) => project.Solution.WithOptions(options).GetProject(project.Id)!; public static TextDocument? GetTextDocument(this Project project, DocumentId? documentId) => project.Solution.GetTextDocument(documentId); internal static DocumentId? GetDocumentForExternalLocation(this Project project, Location location) { Debug.Assert(location.Kind == LocationKind.ExternalFile); return project.GetDocumentIdWithFilePath(location.GetLineSpan().Path); } internal static DocumentId? GetDocumentForFile(this Project project, AdditionalText additionalText) => project.GetDocumentIdWithFilePath(additionalText.Path); private static DocumentId? GetDocumentIdWithFilePath(this Project project, string filePath) => project.Solution.GetDocumentIdsWithFilePath(filePath).FirstOrDefault(id => id.ProjectId == project.Id); public static Document GetRequiredDocument(this Project project, DocumentId documentId) { var document = project.GetDocument(documentId); if (document == null) { throw new InvalidOperationException(WorkspaceExtensionsResources.The_solution_does_not_contain_the_specified_document); } return document; } public static TextDocument GetRequiredTextDocument(this Project project, DocumentId documentId) { var document = project.GetTextDocument(documentId); if (document == null) { throw new InvalidOperationException(WorkspaceExtensionsResources.The_solution_does_not_contain_the_specified_document); } return document; } } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/VisualStudio/Core/Def/Implementation/Preview/ReferenceChange.AnalyzerReferenceChange.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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; using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Preview { internal abstract partial class ReferenceChange : AbstractChange { private sealed class AnalyzerReferenceChange : ReferenceChange { private readonly AnalyzerReference _reference; public AnalyzerReferenceChange(AnalyzerReference reference, ProjectId projectId, string projectName, bool isAdded, PreviewEngine engine) : base(projectId, projectName, isAdded, engine) { _reference = reference; } internal override Solution AddToSolution(Solution solution) => solution.AddAnalyzerReference(this.ProjectId, _reference); internal override Solution RemoveFromSolution(Solution solution) => solution.RemoveAnalyzerReference(this.ProjectId, _reference); protected override string GetDisplayText() { var display = _reference.Display ?? ServicesVSResources.Unknown1; return string.Format(ServicesVSResources.Analyzer_reference_to_0_in_project_1, display, this.ProjectName); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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; using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Preview { internal abstract partial class ReferenceChange : AbstractChange { private sealed class AnalyzerReferenceChange : ReferenceChange { private readonly AnalyzerReference _reference; public AnalyzerReferenceChange(AnalyzerReference reference, ProjectId projectId, string projectName, bool isAdded, PreviewEngine engine) : base(projectId, projectName, isAdded, engine) { _reference = reference; } internal override Solution AddToSolution(Solution solution) => solution.AddAnalyzerReference(this.ProjectId, _reference); internal override Solution RemoveFromSolution(Solution solution) => solution.RemoveAnalyzerReference(this.ProjectId, _reference); protected override string GetDisplayText() { var display = _reference.Display ?? ServicesVSResources.Unknown1; return string.Format(ServicesVSResources.Analyzer_reference_to_0_in_project_1, display, this.ProjectName); } } } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/Scripting/VisualBasic/xlf/VBScriptingResources.de.xlf
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="de" original="../VBScriptingResources.resx"> <body> <trans-unit id="LogoLine1"> <source>Microsoft (R) Visual Basic Interactive Compiler version {0}</source> <target state="translated">Microsoft (R) Visual Basic – interaktive Compilerversion {0}</target> <note /> </trans-unit> <trans-unit id="LogoLine2"> <source>Copyright (C) Microsoft Corporation. All rights reserved.</source> <target state="translated">Copyright (C) Microsoft Corporation. Alle Rechte vorbehalten.</target> <note /> </trans-unit> <trans-unit id="InteractiveHelp"> <source>Usage: vbi [options] [script-file.vbx] [-- script-arguments] If script-file is specified executes the script, otherwise launches an interactive REPL (Read Eval Print Loop). Options: /help Display this usage message (Short form: /?) /version Display the version and exit /reference:&lt;alias&gt;=&lt;file&gt; Reference metadata from the specified assembly file using the given alias (Short form: /r) /reference:&lt;file list&gt; Reference metadata from the specified assembly files (Short form: /r) /referencePath:&lt;path list&gt; List of paths where to look for metadata references specified as unrooted paths. (Short form: /rp) /using:&lt;namespace&gt; Define global namespace using (Short form: /u) /define:&lt;name&gt;=&lt;value&gt;,... Declare global conditional compilation symbol(s) (Short form: /d) @&lt;file&gt; Read response file for more options </source> <target state="translated">Syntax: vbi [optionen] [script-file.vbx] [-- script-arguments] Bei Angabe von script-file wird das Skript ausgeführt. Andernfalls wird eine interaktive REPL (read–eval–print-Loop) gestartet. Optionen: /help Anzeige dieser Syntaxmeldung (Kurzform: /?) /version Anzeige der Version und Beendigung /reference:&lt;alias&gt;=&lt;datei&gt; Verweis auf Metadaten aus der angegebenen Assemblydatei über den angegebenen Alias (Kurzform: /r) /reference:&lt;dateiliste&gt; Verweis auf Metadaten aus den angegebenen Assemblydateien (Kurzform: /r) /referencePath:&lt;pfadliste&gt; Liste von Pfaden, in denen nach Metadatenverweisen gesucht wird, ohne Angabe des Stammverzeichnisses (Kurzform: /rp) /using:&lt;namespace&gt; Definition eines globalen Namespace mit "using" (Kurzform: /u) /define:&lt;name&gt;=&lt;wert&gt;,... Deklaration globaler Symbole für die bedingte Kompilierung (Kurzform: /d) @&lt;datei&gt; Lesen der Antwortdatei mit weiteren Optionen </target> <note /> </trans-unit> <trans-unit id="ExceptionEscapeWithoutQuote"> <source>Cannot escape non-printable characters in Visual Basic notation unless quotes are used.</source> <target state="translated">Nicht druckbare Zeichen können in der Visual Basic-Notation nur mit Escapezeichen versehen werden, wenn Anführungszeichen verwendet werden.</target> <note /> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="de" original="../VBScriptingResources.resx"> <body> <trans-unit id="LogoLine1"> <source>Microsoft (R) Visual Basic Interactive Compiler version {0}</source> <target state="translated">Microsoft (R) Visual Basic – interaktive Compilerversion {0}</target> <note /> </trans-unit> <trans-unit id="LogoLine2"> <source>Copyright (C) Microsoft Corporation. All rights reserved.</source> <target state="translated">Copyright (C) Microsoft Corporation. Alle Rechte vorbehalten.</target> <note /> </trans-unit> <trans-unit id="InteractiveHelp"> <source>Usage: vbi [options] [script-file.vbx] [-- script-arguments] If script-file is specified executes the script, otherwise launches an interactive REPL (Read Eval Print Loop). Options: /help Display this usage message (Short form: /?) /version Display the version and exit /reference:&lt;alias&gt;=&lt;file&gt; Reference metadata from the specified assembly file using the given alias (Short form: /r) /reference:&lt;file list&gt; Reference metadata from the specified assembly files (Short form: /r) /referencePath:&lt;path list&gt; List of paths where to look for metadata references specified as unrooted paths. (Short form: /rp) /using:&lt;namespace&gt; Define global namespace using (Short form: /u) /define:&lt;name&gt;=&lt;value&gt;,... Declare global conditional compilation symbol(s) (Short form: /d) @&lt;file&gt; Read response file for more options </source> <target state="translated">Syntax: vbi [optionen] [script-file.vbx] [-- script-arguments] Bei Angabe von script-file wird das Skript ausgeführt. Andernfalls wird eine interaktive REPL (read–eval–print-Loop) gestartet. Optionen: /help Anzeige dieser Syntaxmeldung (Kurzform: /?) /version Anzeige der Version und Beendigung /reference:&lt;alias&gt;=&lt;datei&gt; Verweis auf Metadaten aus der angegebenen Assemblydatei über den angegebenen Alias (Kurzform: /r) /reference:&lt;dateiliste&gt; Verweis auf Metadaten aus den angegebenen Assemblydateien (Kurzform: /r) /referencePath:&lt;pfadliste&gt; Liste von Pfaden, in denen nach Metadatenverweisen gesucht wird, ohne Angabe des Stammverzeichnisses (Kurzform: /rp) /using:&lt;namespace&gt; Definition eines globalen Namespace mit "using" (Kurzform: /u) /define:&lt;name&gt;=&lt;wert&gt;,... Deklaration globaler Symbole für die bedingte Kompilierung (Kurzform: /d) @&lt;datei&gt; Lesen der Antwortdatei mit weiteren Optionen </target> <note /> </trans-unit> <trans-unit id="ExceptionEscapeWithoutQuote"> <source>Cannot escape non-printable characters in Visual Basic notation unless quotes are used.</source> <target state="translated">Nicht druckbare Zeichen können in der Visual Basic-Notation nur mit Escapezeichen versehen werden, wenn Anführungszeichen verwendet werden.</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/CodeStyle/VisualBasic/CodeFixes/xlf/VBCodeStyleFixesResources.tr.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="tr" original="../VBCodeStyleFixesResources.resx"> <body> <trans-unit id="EmptyResource"> <source>Remove this value when another is added.</source> <target state="translated">Başka bir değer eklendiğinde bu değeri kaldırın.</target> <note>https://github.com/Microsoft/msbuild/issues/1661</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="tr" original="../VBCodeStyleFixesResources.resx"> <body> <trans-unit id="EmptyResource"> <source>Remove this value when another is added.</source> <target state="translated">Başka bir değer eklendiğinde bu değeri kaldırın.</target> <note>https://github.com/Microsoft/msbuild/issues/1661</note> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/EditorFeatures/XunitHook/XunitDisposeHook.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace Microsoft.CodeAnalysis.Test.Utilities { internal sealed class XunitDisposeHook : MarshalByRefObject { [SuppressMessage("Performance", "CA1822:Mark members as static", Justification = "Invoked across app domains")] public void Execute() { if (!AppDomain.CurrentDomain.IsDefaultAppDomain()) throw new InvalidOperationException(); var xunitUtilities = AppDomain.CurrentDomain.GetAssemblies().Where(static assembly => assembly.GetName().Name.StartsWith("xunit.runner.utility")).ToArray(); foreach (var xunitUtility in xunitUtilities) { var appDomainManagerType = xunitUtility.GetType("Xunit.AppDomainManager_AppDomain"); if (appDomainManagerType is null) continue; // AppDomainManager_AppDomain.Dispose() calls AppDomain.Unload(), which is unfortunately not reliable // when the test creates STA COM objects. Since this call to Unload() only occurs at the end of testing // (immediately before the process is going to close anyway), we can simply hot-patch the executable // code in Dispose() to return without taking any action. // // This is a workaround for https://github.com/xunit/xunit/issues/2097. The fix in // https://github.com/xunit/xunit/pull/2192 was not viable because xunit v2 is no longer shipping // updates. Once xunit v3 is available, it will no longer be necessary. var method = appDomainManagerType.GetMethod("Dispose"); RuntimeHelpers.PrepareMethod(method.MethodHandle); var functionPointer = method.MethodHandle.GetFunctionPointer(); switch (RuntimeInformation.ProcessArchitecture) { case Architecture.X86: case Architecture.X64: // 😱 Overwrite the compiled method to just return. // Note that the same sequence works for x86 and x64. // ret Marshal.WriteByte(functionPointer, 0xC3); break; default: 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.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace Microsoft.CodeAnalysis.Test.Utilities { internal sealed class XunitDisposeHook : MarshalByRefObject { [SuppressMessage("Performance", "CA1822:Mark members as static", Justification = "Invoked across app domains")] public void Execute() { if (!AppDomain.CurrentDomain.IsDefaultAppDomain()) throw new InvalidOperationException(); var xunitUtilities = AppDomain.CurrentDomain.GetAssemblies().Where(static assembly => assembly.GetName().Name.StartsWith("xunit.runner.utility")).ToArray(); foreach (var xunitUtility in xunitUtilities) { var appDomainManagerType = xunitUtility.GetType("Xunit.AppDomainManager_AppDomain"); if (appDomainManagerType is null) continue; // AppDomainManager_AppDomain.Dispose() calls AppDomain.Unload(), which is unfortunately not reliable // when the test creates STA COM objects. Since this call to Unload() only occurs at the end of testing // (immediately before the process is going to close anyway), we can simply hot-patch the executable // code in Dispose() to return without taking any action. // // This is a workaround for https://github.com/xunit/xunit/issues/2097. The fix in // https://github.com/xunit/xunit/pull/2192 was not viable because xunit v2 is no longer shipping // updates. Once xunit v3 is available, it will no longer be necessary. var method = appDomainManagerType.GetMethod("Dispose"); RuntimeHelpers.PrepareMethod(method.MethodHandle); var functionPointer = method.MethodHandle.GetFunctionPointer(); switch (RuntimeInformation.ProcessArchitecture) { case Architecture.X86: case Architecture.X64: // 😱 Overwrite the compiled method to just return. // Note that the same sequence works for x86 and x64. // ret Marshal.WriteByte(functionPointer, 0xC3); break; default: throw new NotSupportedException(); } } } } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/VisualStudio/CSharp/Impl/Options/AutomationObject/AutomationObject.OnOff.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Editor.Shared.Options; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options { public partial class AutomationObject { public int AutoInsertAsteriskForNewLinesOfBlockComments { get { return GetBooleanOption(FeatureOnOffOptions.AutoInsertBlockCommentStartString); } set { SetBooleanOption(FeatureOnOffOptions.AutoInsertBlockCommentStartString, value); } } public int DisplayLineSeparators { get { return GetBooleanOption(FeatureOnOffOptions.LineSeparator); } set { SetBooleanOption(FeatureOnOffOptions.LineSeparator, value); } } public int EnableHighlightRelatedKeywords { get { return GetBooleanOption(FeatureOnOffOptions.KeywordHighlighting); } set { SetBooleanOption(FeatureOnOffOptions.KeywordHighlighting, value); } } public int EnterOutliningModeOnOpen { get { return GetBooleanOption(FeatureOnOffOptions.Outlining); } set { SetBooleanOption(FeatureOnOffOptions.Outlining, value); } } public int HighlightReferences { get { return GetBooleanOption(FeatureOnOffOptions.ReferenceHighlighting); } set { SetBooleanOption(FeatureOnOffOptions.ReferenceHighlighting, value); } } public int Refactoring_Verification_Enabled { get { return GetBooleanOption(FeatureOnOffOptions.RefactoringVerification); } set { SetBooleanOption(FeatureOnOffOptions.RefactoringVerification, value); } } public int RenameSmartTagEnabled { get { return GetBooleanOption(FeatureOnOffOptions.RenameTracking); } set { SetBooleanOption(FeatureOnOffOptions.RenameTracking, value); } } public int RenameTrackingPreview { get { return GetBooleanOption(FeatureOnOffOptions.RenameTrackingPreview); } set { SetBooleanOption(FeatureOnOffOptions.RenameTrackingPreview, value); } } public int NavigateToDecompiledSources { get { return GetBooleanOption(FeatureOnOffOptions.NavigateToDecompiledSources); } set { SetBooleanOption(FeatureOnOffOptions.NavigateToDecompiledSources, value); } } public int UseEnhancedColors { get { return GetOption(FeatureOnOffOptions.UseEnhancedColors); } set { SetOption(FeatureOnOffOptions.UseEnhancedColors, value); } } public int AddImportsOnPaste { get { return GetBooleanOption(FeatureOnOffOptions.AddImportsOnPaste); } set { SetBooleanOption(FeatureOnOffOptions.AddImportsOnPaste, value); } } public int OfferRemoveUnusedReferences { get { return GetBooleanOption(FeatureOnOffOptions.OfferRemoveUnusedReferences); } set { SetBooleanOption(FeatureOnOffOptions.OfferRemoveUnusedReferences, value); } } public int AutomaticallyCompleteStatementOnSemicolon { get { return GetBooleanOption(FeatureOnOffOptions.AutomaticallyCompleteStatementOnSemicolon); } set { SetBooleanOption(FeatureOnOffOptions.AutomaticallyCompleteStatementOnSemicolon, value); } } public int SkipAnalyzersForImplicitlyTriggeredBuilds { get { return GetBooleanOption(FeatureOnOffOptions.SkipAnalyzersForImplicitlyTriggeredBuilds); } set { SetBooleanOption(FeatureOnOffOptions.SkipAnalyzersForImplicitlyTriggeredBuilds, value); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Editor.Shared.Options; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options { public partial class AutomationObject { public int AutoInsertAsteriskForNewLinesOfBlockComments { get { return GetBooleanOption(FeatureOnOffOptions.AutoInsertBlockCommentStartString); } set { SetBooleanOption(FeatureOnOffOptions.AutoInsertBlockCommentStartString, value); } } public int DisplayLineSeparators { get { return GetBooleanOption(FeatureOnOffOptions.LineSeparator); } set { SetBooleanOption(FeatureOnOffOptions.LineSeparator, value); } } public int EnableHighlightRelatedKeywords { get { return GetBooleanOption(FeatureOnOffOptions.KeywordHighlighting); } set { SetBooleanOption(FeatureOnOffOptions.KeywordHighlighting, value); } } public int EnterOutliningModeOnOpen { get { return GetBooleanOption(FeatureOnOffOptions.Outlining); } set { SetBooleanOption(FeatureOnOffOptions.Outlining, value); } } public int HighlightReferences { get { return GetBooleanOption(FeatureOnOffOptions.ReferenceHighlighting); } set { SetBooleanOption(FeatureOnOffOptions.ReferenceHighlighting, value); } } public int Refactoring_Verification_Enabled { get { return GetBooleanOption(FeatureOnOffOptions.RefactoringVerification); } set { SetBooleanOption(FeatureOnOffOptions.RefactoringVerification, value); } } public int RenameSmartTagEnabled { get { return GetBooleanOption(FeatureOnOffOptions.RenameTracking); } set { SetBooleanOption(FeatureOnOffOptions.RenameTracking, value); } } public int RenameTrackingPreview { get { return GetBooleanOption(FeatureOnOffOptions.RenameTrackingPreview); } set { SetBooleanOption(FeatureOnOffOptions.RenameTrackingPreview, value); } } public int NavigateToDecompiledSources { get { return GetBooleanOption(FeatureOnOffOptions.NavigateToDecompiledSources); } set { SetBooleanOption(FeatureOnOffOptions.NavigateToDecompiledSources, value); } } public int UseEnhancedColors { get { return GetOption(FeatureOnOffOptions.UseEnhancedColors); } set { SetOption(FeatureOnOffOptions.UseEnhancedColors, value); } } public int AddImportsOnPaste { get { return GetBooleanOption(FeatureOnOffOptions.AddImportsOnPaste); } set { SetBooleanOption(FeatureOnOffOptions.AddImportsOnPaste, value); } } public int OfferRemoveUnusedReferences { get { return GetBooleanOption(FeatureOnOffOptions.OfferRemoveUnusedReferences); } set { SetBooleanOption(FeatureOnOffOptions.OfferRemoveUnusedReferences, value); } } public int AutomaticallyCompleteStatementOnSemicolon { get { return GetBooleanOption(FeatureOnOffOptions.AutomaticallyCompleteStatementOnSemicolon); } set { SetBooleanOption(FeatureOnOffOptions.AutomaticallyCompleteStatementOnSemicolon, value); } } public int SkipAnalyzersForImplicitlyTriggeredBuilds { get { return GetBooleanOption(FeatureOnOffOptions.SkipAnalyzersForImplicitlyTriggeredBuilds); } set { SetBooleanOption(FeatureOnOffOptions.SkipAnalyzersForImplicitlyTriggeredBuilds, value); } } } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/Compilers/VisualBasic/Portable/Syntax/InternalSyntax/SyntaxNodeFactories.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. '----------------------------------------------------------------------------------------------------------- ' Contains hand-written factories for the SyntaxNodes. Most factories are ' code-generated into SyntaxNodes.vb, but some are easier to hand-write. '----------------------------------------------------------------------------------------------------------- Imports Microsoft.CodeAnalysis.Syntax.InternalSyntax Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports InternalSyntax = Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax Partial Friend Class SyntaxFactory Friend Shared Function IntegerLiteralToken(text As String, base As LiteralBase, typeSuffix As TypeCharacter, value As ULong, leadingTrivia As GreenNode, trailingTrivia As GreenNode) As IntegerLiteralTokenSyntax Debug.Assert(text IsNot Nothing) Select Case typeSuffix Case TypeCharacter.ShortLiteral Return New IntegerLiteralTokenSyntax(Of Short)(SyntaxKind.IntegerLiteralToken, text, leadingTrivia, trailingTrivia, base, typeSuffix, CShort(value)) Case TypeCharacter.UShortLiteral Return New IntegerLiteralTokenSyntax(Of UShort)(SyntaxKind.IntegerLiteralToken, text, leadingTrivia, trailingTrivia, base, typeSuffix, CUShort(value)) Case TypeCharacter.IntegerLiteral, TypeCharacter.Integer Return New IntegerLiteralTokenSyntax(Of Integer)(SyntaxKind.IntegerLiteralToken, text, leadingTrivia, trailingTrivia, base, typeSuffix, CInt(value)) Case TypeCharacter.UIntegerLiteral Return New IntegerLiteralTokenSyntax(Of UInteger)(SyntaxKind.IntegerLiteralToken, text, leadingTrivia, trailingTrivia, base, typeSuffix, CUInt(value)) Case TypeCharacter.LongLiteral, TypeCharacter.Long Return New IntegerLiteralTokenSyntax(Of Long)(SyntaxKind.IntegerLiteralToken, text, leadingTrivia, trailingTrivia, base, typeSuffix, CLng(value)) Case TypeCharacter.ULongLiteral Return New IntegerLiteralTokenSyntax(Of ULong)(SyntaxKind.IntegerLiteralToken, text, leadingTrivia, trailingTrivia, base, typeSuffix, value) Case TypeCharacter.None Dim useIntegerType As Boolean = False If base = LiteralBase.Decimal Then useIntegerType = (value <= Integer.MaxValue) Else useIntegerType = ((value And (Not &HFFFFFFFFUL)) = 0) End If If useIntegerType Then Return New IntegerLiteralTokenSyntax(Of Integer)(SyntaxKind.IntegerLiteralToken, text, leadingTrivia, trailingTrivia, base, typeSuffix, CInt(value)) Else Return New IntegerLiteralTokenSyntax(Of Long)(SyntaxKind.IntegerLiteralToken, text, leadingTrivia, trailingTrivia, base, typeSuffix, CLng(value)) End If Case Else Throw New ArgumentException(NameOf(typeSuffix)) End Select End Function Friend Shared Function FloatingLiteralToken(text As String, typeSuffix As TypeCharacter, value As Double, leadingTrivia As GreenNode, trailingTrivia As GreenNode) As FloatingLiteralTokenSyntax Debug.Assert(text IsNot Nothing) Select Case typeSuffix Case TypeCharacter.DoubleLiteral, TypeCharacter.Double, TypeCharacter.None Return New FloatingLiteralTokenSyntax(Of Double)(SyntaxKind.FloatingLiteralToken, text, leadingTrivia, trailingTrivia, typeSuffix, value) Case TypeCharacter.SingleLiteral, TypeCharacter.Single Return New FloatingLiteralTokenSyntax(Of Single)(SyntaxKind.FloatingLiteralToken, text, leadingTrivia, trailingTrivia, typeSuffix, CSng(value)) Case Else Throw New ArgumentException(NameOf(typeSuffix)) End Select End Function ''' <summary> ''' Create an identifier node without brackets or type character. ''' </summary> Friend Shared Function Identifier(text As String, leadingTrivia As GreenNode, trailingTrivia As GreenNode) As IdentifierTokenSyntax Debug.Assert(text IsNot Nothing) Return New SimpleIdentifierSyntax(SyntaxKind.IdentifierToken, Nothing, Nothing, text, leadingTrivia, trailingTrivia) End Function ''' <summary> ''' Create an identifier node with brackets or type character. ''' </summary> Friend Shared Function Identifier(text As String, possibleKeywordKind As SyntaxKind, isBracketed As Boolean, identifierText As String, typeCharacter As TypeCharacter, leadingTrivia As GreenNode, trailingTrivia As GreenNode) As IdentifierTokenSyntax Debug.Assert(text IsNot Nothing) Return New ComplexIdentifierSyntax(SyntaxKind.IdentifierToken, Nothing, Nothing, text, leadingTrivia, trailingTrivia, possibleKeywordKind, isBracketed, identifierText, typeCharacter) End Function ''' <summary> ''' Create an identifier node without brackets or type character or trivia. ''' </summary> Friend Shared Function Identifier(text As String) As IdentifierTokenSyntax Debug.Assert(text IsNot Nothing) Return New SimpleIdentifierSyntax(SyntaxKind.IdentifierToken, Nothing, Nothing, text, Nothing, Nothing) End Function ''' <summary> ''' Create a missing identifier. ''' </summary> Friend Shared Function MissingIdentifier() As IdentifierTokenSyntax Return New SimpleIdentifierSyntax(SyntaxKind.IdentifierToken, Nothing, Nothing, "", Nothing, Nothing) End Function ''' <summary> ''' Create a missing contextual keyword. ''' </summary> Friend Shared Function MissingIdentifier(kind As SyntaxKind) As IdentifierTokenSyntax Return New ComplexIdentifierSyntax(SyntaxKind.IdentifierToken, Nothing, Nothing, "", Nothing, Nothing, kind, False, "", TypeCharacter.None) End Function ''' <summary> ''' Create a missing keyword. ''' </summary> Friend Shared Function MissingKeyword(kind As SyntaxKind) As KeywordSyntax Return New KeywordSyntax(kind, "", Nothing, Nothing) End Function ''' <summary> ''' Create a missing punctuation mark. ''' </summary> Friend Shared Function MissingPunctuation(kind As SyntaxKind) As PunctuationSyntax Return New PunctuationSyntax(kind, "", Nothing, Nothing) End Function ''' <summary> ''' Create a missing string literal. ''' </summary> Friend Shared Function MissingStringLiteral() As StringLiteralTokenSyntax Return StringLiteralToken("", "", Nothing, Nothing) End Function ''' <summary> ''' Create a missing character literal. ''' </summary> Friend Shared Function MissingCharacterLiteralToken() As CharacterLiteralTokenSyntax Return CharacterLiteralToken("", Nothing, Nothing, Nothing) End Function ''' <summary> ''' Create a missing integer literal. ''' </summary> Friend Shared Function MissingIntegerLiteralToken() As IntegerLiteralTokenSyntax Return IntegerLiteralToken("", LiteralBase.Decimal, TypeCharacter.None, Nothing, Nothing, Nothing) End Function ''' <summary> ''' Creates a copy of a token. ''' <para name="err"></para> ''' <para name="trivia"></para> ''' </summary> ''' <returns>The new token</returns> Friend Shared Function MissingToken(kind As SyntaxKind) As SyntaxToken Dim t As SyntaxToken Select Case kind Case SyntaxKind.StatementTerminatorToken t = SyntaxFactory.Token(Nothing, SyntaxKind.StatementTerminatorToken, Nothing, String.Empty) Case SyntaxKind.EndOfFileToken t = SyntaxFactory.EndOfFileToken() Case SyntaxKind.AddHandlerKeyword, SyntaxKind.AddressOfKeyword, SyntaxKind.AliasKeyword, SyntaxKind.AndKeyword, SyntaxKind.AndAlsoKeyword, SyntaxKind.AsKeyword, SyntaxKind.BooleanKeyword, SyntaxKind.ByRefKeyword, SyntaxKind.ByteKeyword, SyntaxKind.ByValKeyword, SyntaxKind.CallKeyword, SyntaxKind.CaseKeyword, SyntaxKind.CatchKeyword, SyntaxKind.CBoolKeyword, SyntaxKind.CByteKeyword, SyntaxKind.CCharKeyword, SyntaxKind.CDateKeyword, SyntaxKind.CDecKeyword, SyntaxKind.CDblKeyword, SyntaxKind.CharKeyword, SyntaxKind.CIntKeyword, SyntaxKind.ClassKeyword, SyntaxKind.CLngKeyword, SyntaxKind.CObjKeyword, SyntaxKind.ConstKeyword, SyntaxKind.ContinueKeyword, SyntaxKind.CSByteKeyword, SyntaxKind.CShortKeyword, SyntaxKind.CSngKeyword, SyntaxKind.CStrKeyword, SyntaxKind.CTypeKeyword, SyntaxKind.CUIntKeyword, SyntaxKind.CULngKeyword, SyntaxKind.CUShortKeyword, SyntaxKind.DateKeyword, SyntaxKind.DecimalKeyword, SyntaxKind.DeclareKeyword, SyntaxKind.DefaultKeyword, SyntaxKind.DelegateKeyword, SyntaxKind.DimKeyword, SyntaxKind.DirectCastKeyword, SyntaxKind.DoKeyword, SyntaxKind.DoubleKeyword, SyntaxKind.EachKeyword, SyntaxKind.ElseKeyword, SyntaxKind.ElseIfKeyword, SyntaxKind.EndKeyword, SyntaxKind.EnumKeyword, SyntaxKind.EraseKeyword, SyntaxKind.ErrorKeyword, SyntaxKind.EventKeyword, SyntaxKind.ExitKeyword, SyntaxKind.FalseKeyword, SyntaxKind.FinallyKeyword, SyntaxKind.ForKeyword, SyntaxKind.FriendKeyword, SyntaxKind.FunctionKeyword, SyntaxKind.GetKeyword, SyntaxKind.GetTypeKeyword, SyntaxKind.GetXmlNamespaceKeyword, SyntaxKind.GlobalKeyword, SyntaxKind.GoToKeyword, SyntaxKind.HandlesKeyword, SyntaxKind.IfKeyword, SyntaxKind.ImplementsKeyword, SyntaxKind.ImportsKeyword, SyntaxKind.InKeyword, SyntaxKind.InheritsKeyword, SyntaxKind.IntegerKeyword, SyntaxKind.InterfaceKeyword, SyntaxKind.IsKeyword, SyntaxKind.IsNotKeyword, SyntaxKind.LetKeyword, SyntaxKind.LibKeyword, SyntaxKind.LikeKeyword, SyntaxKind.LongKeyword, SyntaxKind.LoopKeyword, SyntaxKind.MeKeyword, SyntaxKind.ModKeyword, SyntaxKind.ModuleKeyword, SyntaxKind.MustInheritKeyword, SyntaxKind.MustOverrideKeyword, SyntaxKind.MyBaseKeyword, SyntaxKind.MyClassKeyword, SyntaxKind.NameOfKeyword, SyntaxKind.NamespaceKeyword, SyntaxKind.NarrowingKeyword, SyntaxKind.NextKeyword, SyntaxKind.NewKeyword, SyntaxKind.NotKeyword, SyntaxKind.NothingKeyword, SyntaxKind.NotInheritableKeyword, SyntaxKind.NotOverridableKeyword, SyntaxKind.ObjectKeyword, SyntaxKind.OfKeyword, SyntaxKind.OnKeyword, SyntaxKind.OperatorKeyword, SyntaxKind.OptionKeyword, SyntaxKind.OptionalKeyword, SyntaxKind.OrKeyword, SyntaxKind.OrElseKeyword, SyntaxKind.OverloadsKeyword, SyntaxKind.OverridableKeyword, SyntaxKind.OverridesKeyword, SyntaxKind.ParamArrayKeyword, SyntaxKind.PartialKeyword, SyntaxKind.PrivateKeyword, SyntaxKind.PropertyKeyword, SyntaxKind.ProtectedKeyword, SyntaxKind.PublicKeyword, SyntaxKind.RaiseEventKeyword, SyntaxKind.ReadOnlyKeyword, SyntaxKind.ReDimKeyword, SyntaxKind.REMKeyword, SyntaxKind.RemoveHandlerKeyword, SyntaxKind.ResumeKeyword, SyntaxKind.ReturnKeyword, SyntaxKind.SByteKeyword, SyntaxKind.SelectKeyword, SyntaxKind.SetKeyword, SyntaxKind.ShadowsKeyword, SyntaxKind.SharedKeyword, SyntaxKind.ShortKeyword, SyntaxKind.SingleKeyword, SyntaxKind.StaticKeyword, SyntaxKind.StepKeyword, SyntaxKind.StopKeyword, SyntaxKind.StringKeyword, SyntaxKind.StructureKeyword, SyntaxKind.SubKeyword, SyntaxKind.SyncLockKeyword, SyntaxKind.ThenKeyword, SyntaxKind.ThrowKeyword, SyntaxKind.ToKeyword, SyntaxKind.TrueKeyword, SyntaxKind.TryKeyword, SyntaxKind.TryCastKeyword, SyntaxKind.TypeOfKeyword, SyntaxKind.UIntegerKeyword, SyntaxKind.ULongKeyword, SyntaxKind.UShortKeyword, SyntaxKind.UsingKeyword, SyntaxKind.WhenKeyword, SyntaxKind.WhileKeyword, SyntaxKind.WideningKeyword, SyntaxKind.WithKeyword, SyntaxKind.WithEventsKeyword, SyntaxKind.WriteOnlyKeyword, SyntaxKind.XorKeyword, SyntaxKind.EndIfKeyword, SyntaxKind.GosubKeyword, SyntaxKind.VariantKeyword, SyntaxKind.WendKeyword, SyntaxKind.OutKeyword t = SyntaxFactory.MissingKeyword(kind) Case SyntaxKind.AggregateKeyword, SyntaxKind.AllKeyword, SyntaxKind.AnsiKeyword, SyntaxKind.AscendingKeyword, SyntaxKind.AssemblyKeyword, SyntaxKind.AutoKeyword, SyntaxKind.BinaryKeyword, SyntaxKind.ByKeyword, SyntaxKind.CompareKeyword, SyntaxKind.CustomKeyword, SyntaxKind.DescendingKeyword, SyntaxKind.DisableKeyword, SyntaxKind.DistinctKeyword, SyntaxKind.EnableKeyword, SyntaxKind.EqualsKeyword, SyntaxKind.ExplicitKeyword, SyntaxKind.ExternalSourceKeyword, SyntaxKind.ExternalChecksumKeyword, SyntaxKind.FromKeyword, SyntaxKind.GroupKeyword, SyntaxKind.InferKeyword, SyntaxKind.IntoKeyword, SyntaxKind.IsFalseKeyword, SyntaxKind.IsTrueKeyword, SyntaxKind.JoinKeyword, SyntaxKind.KeyKeyword, SyntaxKind.MidKeyword, SyntaxKind.OffKeyword, SyntaxKind.OrderKeyword, SyntaxKind.PreserveKeyword, SyntaxKind.RegionKeyword, SyntaxKind.ReferenceKeyword, SyntaxKind.SkipKeyword, SyntaxKind.StrictKeyword, SyntaxKind.TextKeyword, SyntaxKind.TakeKeyword, SyntaxKind.UnicodeKeyword, SyntaxKind.UntilKeyword, SyntaxKind.WarningKeyword, SyntaxKind.WhereKeyword ' These are identifiers that have a contextual kind Return SyntaxFactory.MissingIdentifier(kind) Case SyntaxKind.ExclamationToken, SyntaxKind.CommaToken, SyntaxKind.HashToken, SyntaxKind.AmpersandToken, SyntaxKind.SingleQuoteToken, SyntaxKind.OpenParenToken, SyntaxKind.CloseParenToken, SyntaxKind.OpenBraceToken, SyntaxKind.CloseBraceToken, SyntaxKind.DoubleQuoteToken, SyntaxKind.SemicolonToken, SyntaxKind.AsteriskToken, SyntaxKind.PlusToken, SyntaxKind.MinusToken, SyntaxKind.DotToken, SyntaxKind.SlashToken, SyntaxKind.ColonToken, SyntaxKind.LessThanToken, SyntaxKind.LessThanEqualsToken, SyntaxKind.LessThanGreaterThanToken, SyntaxKind.EqualsToken, SyntaxKind.GreaterThanToken, SyntaxKind.GreaterThanEqualsToken, SyntaxKind.BackslashToken, SyntaxKind.CaretToken, SyntaxKind.ColonEqualsToken, SyntaxKind.AmpersandEqualsToken, SyntaxKind.AsteriskEqualsToken, SyntaxKind.PlusEqualsToken, SyntaxKind.MinusEqualsToken, SyntaxKind.SlashEqualsToken, SyntaxKind.BackslashEqualsToken, SyntaxKind.CaretEqualsToken, SyntaxKind.LessThanLessThanToken, SyntaxKind.GreaterThanGreaterThanToken, SyntaxKind.LessThanLessThanEqualsToken, SyntaxKind.GreaterThanGreaterThanEqualsToken, SyntaxKind.QuestionToken t = SyntaxFactory.MissingPunctuation(kind) Case SyntaxKind.FloatingLiteralToken t = SyntaxFactory.FloatingLiteralToken("", TypeCharacter.None, Nothing, Nothing, Nothing) Case SyntaxKind.DecimalLiteralToken t = SyntaxFactory.DecimalLiteralToken("", TypeCharacter.None, Nothing, Nothing, Nothing) Case SyntaxKind.DateLiteralToken t = SyntaxFactory.DateLiteralToken("", Nothing, Nothing, Nothing) Case SyntaxKind.XmlNameToken t = SyntaxFactory.XmlNameToken("", SyntaxKind.XmlNameToken, Nothing, Nothing) Case SyntaxKind.XmlTextLiteralToken t = SyntaxFactory.XmlTextLiteralToken("", "", Nothing, Nothing) Case SyntaxKind.SlashGreaterThanToken, SyntaxKind.LessThanSlashToken, SyntaxKind.LessThanExclamationMinusMinusToken, SyntaxKind.MinusMinusGreaterThanToken, SyntaxKind.LessThanQuestionToken, SyntaxKind.QuestionGreaterThanToken, SyntaxKind.LessThanPercentEqualsToken, SyntaxKind.PercentGreaterThanToken, SyntaxKind.BeginCDataToken, SyntaxKind.EndCDataToken t = SyntaxFactory.MissingPunctuation(kind) Case SyntaxKind.IdentifierToken t = SyntaxFactory.MissingIdentifier() Case SyntaxKind.IntegerLiteralToken t = MissingIntegerLiteralToken() Case SyntaxKind.StringLiteralToken t = SyntaxFactory.MissingStringLiteral() Case SyntaxKind.CharacterLiteralToken t = SyntaxFactory.MissingCharacterLiteralToken() Case SyntaxKind.InterpolatedStringTextToken t = SyntaxFactory.InterpolatedStringTextToken("", "", Nothing, Nothing) Case Else Throw ExceptionUtilities.UnexpectedValue(kind) End Select Return t End Function Friend Shared Function BadToken(SubKind As SyntaxSubKind, text As String, precedingTrivia As GreenNode, followingTrivia As GreenNode) As BadTokenSyntax Return New BadTokenSyntax(SyntaxKind.BadToken, SubKind, Nothing, Nothing, text, precedingTrivia, followingTrivia) End Function ''' <summary> ''' Create an end-of-text token. ''' </summary> Friend Shared Function EndOfFileToken(precedingTrivia As SyntaxTrivia) As PunctuationSyntax Return New PunctuationSyntax(SyntaxKind.EndOfFileToken, "", precedingTrivia, Nothing) End Function ''' <summary> ''' Create an end-of-text token. ''' </summary> Friend Shared Function EndOfFileToken() As PunctuationSyntax Return New PunctuationSyntax(SyntaxKind.EndOfFileToken, "", Nothing, Nothing) End Function Friend Shared Function Identifier(text As String, isBracketed As Boolean, baseText As String, typeCharacter As TypeCharacter, precedingTrivia As GreenNode, followingTrivia As GreenNode) As IdentifierTokenSyntax Debug.Assert(text IsNot Nothing) Return New ComplexIdentifierSyntax(SyntaxKind.IdentifierToken, Nothing, Nothing, text, precedingTrivia, followingTrivia, SyntaxKind.IdentifierToken, isBracketed, baseText, typeCharacter) End Function Private Shared s_notMissingEmptyToken As PunctuationSyntax = Nothing Friend Shared ReadOnly Property NotMissingEmptyToken() As PunctuationSyntax Get If s_notMissingEmptyToken Is Nothing Then s_notMissingEmptyToken = New PunctuationSyntax(SyntaxKind.EmptyToken, "", Nothing, Nothing) End If Return s_notMissingEmptyToken End Get End Property Private Shared s_missingEmptyToken As PunctuationSyntax = Nothing Friend Shared ReadOnly Property MissingEmptyToken() As PunctuationSyntax Get If s_missingEmptyToken Is Nothing Then s_missingEmptyToken = New PunctuationSyntax(SyntaxKind.EmptyToken, "", Nothing, Nothing) s_missingEmptyToken.ClearFlags(GreenNode.NodeFlags.IsNotMissing) End If Return s_missingEmptyToken End Get End Property Private Shared s_statementTerminatorToken As PunctuationSyntax = Nothing Friend Shared ReadOnly Property StatementTerminatorToken() As PunctuationSyntax Get If s_statementTerminatorToken Is Nothing Then s_statementTerminatorToken = New PunctuationSyntax(SyntaxKind.StatementTerminatorToken, "", Nothing, Nothing) s_statementTerminatorToken.SetFlags(GreenNode.NodeFlags.IsNotMissing) End If Return s_statementTerminatorToken End Get End Property Private Shared s_colonToken As PunctuationSyntax = Nothing Friend Shared ReadOnly Property ColonToken() As PunctuationSyntax Get If s_colonToken Is Nothing Then s_colonToken = New PunctuationSyntax(SyntaxKind.ColonToken, "", Nothing, Nothing) s_colonToken.SetFlags(GreenNode.NodeFlags.IsNotMissing) End If Return s_colonToken End Get End Property Private Shared ReadOnly s_missingExpr As ExpressionSyntax = SyntaxFactory.IdentifierName(SyntaxFactory.Identifier("", Nothing, Nothing)) Friend Shared Function MissingExpression() As ExpressionSyntax Return s_missingExpr End Function Private Shared ReadOnly s_emptyStatement As EmptyStatementSyntax = SyntaxFactory.EmptyStatement(NotMissingEmptyToken) Friend Shared Function EmptyStatement() As EmptyStatementSyntax Return s_emptyStatement End Function Private Shared ReadOnly s_omittedArgument As OmittedArgumentSyntax = SyntaxFactory.OmittedArgument(NotMissingEmptyToken) Friend Shared Function OmittedArgument() As OmittedArgumentSyntax Return s_omittedArgument End Function Public Shared Function TypeBlock(ByVal blockKind As SyntaxKind, ByVal begin As TypeStatementSyntax, ByVal [inherits] As CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of InheritsStatementSyntax), ByVal [implements] As CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of ImplementsStatementSyntax), ByVal members As CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of StatementSyntax), ByVal [end] As EndBlockStatementSyntax) As TypeBlockSyntax Select Case blockKind Case SyntaxKind.ModuleBlock Return SyntaxFactory.ModuleBlock(DirectCast(begin, ModuleStatementSyntax), [inherits], [implements], members, [end]) Case SyntaxKind.ClassBlock Return SyntaxFactory.ClassBlock(DirectCast(begin, ClassStatementSyntax), [inherits], [implements], members, [end]) Case SyntaxKind.StructureBlock Return SyntaxFactory.StructureBlock(DirectCast(begin, StructureStatementSyntax), [inherits], [implements], members, [end]) Case SyntaxKind.InterfaceBlock Return SyntaxFactory.InterfaceBlock(DirectCast(begin, InterfaceStatementSyntax), [inherits], [implements], members, [end]) Case Else Throw ExceptionUtilities.UnexpectedValue(blockKind) End Select End Function Public Shared Function TypeStatement(ByVal statementKind As SyntaxKind, ByVal attributes As CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of GreenNode), ByVal modifiers As CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of GreenNode), ByVal keyword As KeywordSyntax, ByVal identifier As IdentifierTokenSyntax, ByVal typeParameterList As TypeParameterListSyntax) As TypeStatementSyntax Select Case statementKind Case SyntaxKind.ModuleStatement Return SyntaxFactory.ModuleStatement(attributes, modifiers, keyword, identifier, typeParameterList) Case SyntaxKind.ClassStatement Return SyntaxFactory.ClassStatement(attributes, modifiers, keyword, identifier, typeParameterList) Case SyntaxKind.StructureStatement Return SyntaxFactory.StructureStatement(attributes, modifiers, keyword, identifier, typeParameterList) Case SyntaxKind.InterfaceStatement Return SyntaxFactory.InterfaceStatement(attributes, modifiers, keyword, identifier, typeParameterList) Case Else Throw ExceptionUtilities.UnexpectedValue(statementKind) 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. '----------------------------------------------------------------------------------------------------------- ' Contains hand-written factories for the SyntaxNodes. Most factories are ' code-generated into SyntaxNodes.vb, but some are easier to hand-write. '----------------------------------------------------------------------------------------------------------- Imports Microsoft.CodeAnalysis.Syntax.InternalSyntax Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports InternalSyntax = Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax Partial Friend Class SyntaxFactory Friend Shared Function IntegerLiteralToken(text As String, base As LiteralBase, typeSuffix As TypeCharacter, value As ULong, leadingTrivia As GreenNode, trailingTrivia As GreenNode) As IntegerLiteralTokenSyntax Debug.Assert(text IsNot Nothing) Select Case typeSuffix Case TypeCharacter.ShortLiteral Return New IntegerLiteralTokenSyntax(Of Short)(SyntaxKind.IntegerLiteralToken, text, leadingTrivia, trailingTrivia, base, typeSuffix, CShort(value)) Case TypeCharacter.UShortLiteral Return New IntegerLiteralTokenSyntax(Of UShort)(SyntaxKind.IntegerLiteralToken, text, leadingTrivia, trailingTrivia, base, typeSuffix, CUShort(value)) Case TypeCharacter.IntegerLiteral, TypeCharacter.Integer Return New IntegerLiteralTokenSyntax(Of Integer)(SyntaxKind.IntegerLiteralToken, text, leadingTrivia, trailingTrivia, base, typeSuffix, CInt(value)) Case TypeCharacter.UIntegerLiteral Return New IntegerLiteralTokenSyntax(Of UInteger)(SyntaxKind.IntegerLiteralToken, text, leadingTrivia, trailingTrivia, base, typeSuffix, CUInt(value)) Case TypeCharacter.LongLiteral, TypeCharacter.Long Return New IntegerLiteralTokenSyntax(Of Long)(SyntaxKind.IntegerLiteralToken, text, leadingTrivia, trailingTrivia, base, typeSuffix, CLng(value)) Case TypeCharacter.ULongLiteral Return New IntegerLiteralTokenSyntax(Of ULong)(SyntaxKind.IntegerLiteralToken, text, leadingTrivia, trailingTrivia, base, typeSuffix, value) Case TypeCharacter.None Dim useIntegerType As Boolean = False If base = LiteralBase.Decimal Then useIntegerType = (value <= Integer.MaxValue) Else useIntegerType = ((value And (Not &HFFFFFFFFUL)) = 0) End If If useIntegerType Then Return New IntegerLiteralTokenSyntax(Of Integer)(SyntaxKind.IntegerLiteralToken, text, leadingTrivia, trailingTrivia, base, typeSuffix, CInt(value)) Else Return New IntegerLiteralTokenSyntax(Of Long)(SyntaxKind.IntegerLiteralToken, text, leadingTrivia, trailingTrivia, base, typeSuffix, CLng(value)) End If Case Else Throw New ArgumentException(NameOf(typeSuffix)) End Select End Function Friend Shared Function FloatingLiteralToken(text As String, typeSuffix As TypeCharacter, value As Double, leadingTrivia As GreenNode, trailingTrivia As GreenNode) As FloatingLiteralTokenSyntax Debug.Assert(text IsNot Nothing) Select Case typeSuffix Case TypeCharacter.DoubleLiteral, TypeCharacter.Double, TypeCharacter.None Return New FloatingLiteralTokenSyntax(Of Double)(SyntaxKind.FloatingLiteralToken, text, leadingTrivia, trailingTrivia, typeSuffix, value) Case TypeCharacter.SingleLiteral, TypeCharacter.Single Return New FloatingLiteralTokenSyntax(Of Single)(SyntaxKind.FloatingLiteralToken, text, leadingTrivia, trailingTrivia, typeSuffix, CSng(value)) Case Else Throw New ArgumentException(NameOf(typeSuffix)) End Select End Function ''' <summary> ''' Create an identifier node without brackets or type character. ''' </summary> Friend Shared Function Identifier(text As String, leadingTrivia As GreenNode, trailingTrivia As GreenNode) As IdentifierTokenSyntax Debug.Assert(text IsNot Nothing) Return New SimpleIdentifierSyntax(SyntaxKind.IdentifierToken, Nothing, Nothing, text, leadingTrivia, trailingTrivia) End Function ''' <summary> ''' Create an identifier node with brackets or type character. ''' </summary> Friend Shared Function Identifier(text As String, possibleKeywordKind As SyntaxKind, isBracketed As Boolean, identifierText As String, typeCharacter As TypeCharacter, leadingTrivia As GreenNode, trailingTrivia As GreenNode) As IdentifierTokenSyntax Debug.Assert(text IsNot Nothing) Return New ComplexIdentifierSyntax(SyntaxKind.IdentifierToken, Nothing, Nothing, text, leadingTrivia, trailingTrivia, possibleKeywordKind, isBracketed, identifierText, typeCharacter) End Function ''' <summary> ''' Create an identifier node without brackets or type character or trivia. ''' </summary> Friend Shared Function Identifier(text As String) As IdentifierTokenSyntax Debug.Assert(text IsNot Nothing) Return New SimpleIdentifierSyntax(SyntaxKind.IdentifierToken, Nothing, Nothing, text, Nothing, Nothing) End Function ''' <summary> ''' Create a missing identifier. ''' </summary> Friend Shared Function MissingIdentifier() As IdentifierTokenSyntax Return New SimpleIdentifierSyntax(SyntaxKind.IdentifierToken, Nothing, Nothing, "", Nothing, Nothing) End Function ''' <summary> ''' Create a missing contextual keyword. ''' </summary> Friend Shared Function MissingIdentifier(kind As SyntaxKind) As IdentifierTokenSyntax Return New ComplexIdentifierSyntax(SyntaxKind.IdentifierToken, Nothing, Nothing, "", Nothing, Nothing, kind, False, "", TypeCharacter.None) End Function ''' <summary> ''' Create a missing keyword. ''' </summary> Friend Shared Function MissingKeyword(kind As SyntaxKind) As KeywordSyntax Return New KeywordSyntax(kind, "", Nothing, Nothing) End Function ''' <summary> ''' Create a missing punctuation mark. ''' </summary> Friend Shared Function MissingPunctuation(kind As SyntaxKind) As PunctuationSyntax Return New PunctuationSyntax(kind, "", Nothing, Nothing) End Function ''' <summary> ''' Create a missing string literal. ''' </summary> Friend Shared Function MissingStringLiteral() As StringLiteralTokenSyntax Return StringLiteralToken("", "", Nothing, Nothing) End Function ''' <summary> ''' Create a missing character literal. ''' </summary> Friend Shared Function MissingCharacterLiteralToken() As CharacterLiteralTokenSyntax Return CharacterLiteralToken("", Nothing, Nothing, Nothing) End Function ''' <summary> ''' Create a missing integer literal. ''' </summary> Friend Shared Function MissingIntegerLiteralToken() As IntegerLiteralTokenSyntax Return IntegerLiteralToken("", LiteralBase.Decimal, TypeCharacter.None, Nothing, Nothing, Nothing) End Function ''' <summary> ''' Creates a copy of a token. ''' <para name="err"></para> ''' <para name="trivia"></para> ''' </summary> ''' <returns>The new token</returns> Friend Shared Function MissingToken(kind As SyntaxKind) As SyntaxToken Dim t As SyntaxToken Select Case kind Case SyntaxKind.StatementTerminatorToken t = SyntaxFactory.Token(Nothing, SyntaxKind.StatementTerminatorToken, Nothing, String.Empty) Case SyntaxKind.EndOfFileToken t = SyntaxFactory.EndOfFileToken() Case SyntaxKind.AddHandlerKeyword, SyntaxKind.AddressOfKeyword, SyntaxKind.AliasKeyword, SyntaxKind.AndKeyword, SyntaxKind.AndAlsoKeyword, SyntaxKind.AsKeyword, SyntaxKind.BooleanKeyword, SyntaxKind.ByRefKeyword, SyntaxKind.ByteKeyword, SyntaxKind.ByValKeyword, SyntaxKind.CallKeyword, SyntaxKind.CaseKeyword, SyntaxKind.CatchKeyword, SyntaxKind.CBoolKeyword, SyntaxKind.CByteKeyword, SyntaxKind.CCharKeyword, SyntaxKind.CDateKeyword, SyntaxKind.CDecKeyword, SyntaxKind.CDblKeyword, SyntaxKind.CharKeyword, SyntaxKind.CIntKeyword, SyntaxKind.ClassKeyword, SyntaxKind.CLngKeyword, SyntaxKind.CObjKeyword, SyntaxKind.ConstKeyword, SyntaxKind.ContinueKeyword, SyntaxKind.CSByteKeyword, SyntaxKind.CShortKeyword, SyntaxKind.CSngKeyword, SyntaxKind.CStrKeyword, SyntaxKind.CTypeKeyword, SyntaxKind.CUIntKeyword, SyntaxKind.CULngKeyword, SyntaxKind.CUShortKeyword, SyntaxKind.DateKeyword, SyntaxKind.DecimalKeyword, SyntaxKind.DeclareKeyword, SyntaxKind.DefaultKeyword, SyntaxKind.DelegateKeyword, SyntaxKind.DimKeyword, SyntaxKind.DirectCastKeyword, SyntaxKind.DoKeyword, SyntaxKind.DoubleKeyword, SyntaxKind.EachKeyword, SyntaxKind.ElseKeyword, SyntaxKind.ElseIfKeyword, SyntaxKind.EndKeyword, SyntaxKind.EnumKeyword, SyntaxKind.EraseKeyword, SyntaxKind.ErrorKeyword, SyntaxKind.EventKeyword, SyntaxKind.ExitKeyword, SyntaxKind.FalseKeyword, SyntaxKind.FinallyKeyword, SyntaxKind.ForKeyword, SyntaxKind.FriendKeyword, SyntaxKind.FunctionKeyword, SyntaxKind.GetKeyword, SyntaxKind.GetTypeKeyword, SyntaxKind.GetXmlNamespaceKeyword, SyntaxKind.GlobalKeyword, SyntaxKind.GoToKeyword, SyntaxKind.HandlesKeyword, SyntaxKind.IfKeyword, SyntaxKind.ImplementsKeyword, SyntaxKind.ImportsKeyword, SyntaxKind.InKeyword, SyntaxKind.InheritsKeyword, SyntaxKind.IntegerKeyword, SyntaxKind.InterfaceKeyword, SyntaxKind.IsKeyword, SyntaxKind.IsNotKeyword, SyntaxKind.LetKeyword, SyntaxKind.LibKeyword, SyntaxKind.LikeKeyword, SyntaxKind.LongKeyword, SyntaxKind.LoopKeyword, SyntaxKind.MeKeyword, SyntaxKind.ModKeyword, SyntaxKind.ModuleKeyword, SyntaxKind.MustInheritKeyword, SyntaxKind.MustOverrideKeyword, SyntaxKind.MyBaseKeyword, SyntaxKind.MyClassKeyword, SyntaxKind.NameOfKeyword, SyntaxKind.NamespaceKeyword, SyntaxKind.NarrowingKeyword, SyntaxKind.NextKeyword, SyntaxKind.NewKeyword, SyntaxKind.NotKeyword, SyntaxKind.NothingKeyword, SyntaxKind.NotInheritableKeyword, SyntaxKind.NotOverridableKeyword, SyntaxKind.ObjectKeyword, SyntaxKind.OfKeyword, SyntaxKind.OnKeyword, SyntaxKind.OperatorKeyword, SyntaxKind.OptionKeyword, SyntaxKind.OptionalKeyword, SyntaxKind.OrKeyword, SyntaxKind.OrElseKeyword, SyntaxKind.OverloadsKeyword, SyntaxKind.OverridableKeyword, SyntaxKind.OverridesKeyword, SyntaxKind.ParamArrayKeyword, SyntaxKind.PartialKeyword, SyntaxKind.PrivateKeyword, SyntaxKind.PropertyKeyword, SyntaxKind.ProtectedKeyword, SyntaxKind.PublicKeyword, SyntaxKind.RaiseEventKeyword, SyntaxKind.ReadOnlyKeyword, SyntaxKind.ReDimKeyword, SyntaxKind.REMKeyword, SyntaxKind.RemoveHandlerKeyword, SyntaxKind.ResumeKeyword, SyntaxKind.ReturnKeyword, SyntaxKind.SByteKeyword, SyntaxKind.SelectKeyword, SyntaxKind.SetKeyword, SyntaxKind.ShadowsKeyword, SyntaxKind.SharedKeyword, SyntaxKind.ShortKeyword, SyntaxKind.SingleKeyword, SyntaxKind.StaticKeyword, SyntaxKind.StepKeyword, SyntaxKind.StopKeyword, SyntaxKind.StringKeyword, SyntaxKind.StructureKeyword, SyntaxKind.SubKeyword, SyntaxKind.SyncLockKeyword, SyntaxKind.ThenKeyword, SyntaxKind.ThrowKeyword, SyntaxKind.ToKeyword, SyntaxKind.TrueKeyword, SyntaxKind.TryKeyword, SyntaxKind.TryCastKeyword, SyntaxKind.TypeOfKeyword, SyntaxKind.UIntegerKeyword, SyntaxKind.ULongKeyword, SyntaxKind.UShortKeyword, SyntaxKind.UsingKeyword, SyntaxKind.WhenKeyword, SyntaxKind.WhileKeyword, SyntaxKind.WideningKeyword, SyntaxKind.WithKeyword, SyntaxKind.WithEventsKeyword, SyntaxKind.WriteOnlyKeyword, SyntaxKind.XorKeyword, SyntaxKind.EndIfKeyword, SyntaxKind.GosubKeyword, SyntaxKind.VariantKeyword, SyntaxKind.WendKeyword, SyntaxKind.OutKeyword t = SyntaxFactory.MissingKeyword(kind) Case SyntaxKind.AggregateKeyword, SyntaxKind.AllKeyword, SyntaxKind.AnsiKeyword, SyntaxKind.AscendingKeyword, SyntaxKind.AssemblyKeyword, SyntaxKind.AutoKeyword, SyntaxKind.BinaryKeyword, SyntaxKind.ByKeyword, SyntaxKind.CompareKeyword, SyntaxKind.CustomKeyword, SyntaxKind.DescendingKeyword, SyntaxKind.DisableKeyword, SyntaxKind.DistinctKeyword, SyntaxKind.EnableKeyword, SyntaxKind.EqualsKeyword, SyntaxKind.ExplicitKeyword, SyntaxKind.ExternalSourceKeyword, SyntaxKind.ExternalChecksumKeyword, SyntaxKind.FromKeyword, SyntaxKind.GroupKeyword, SyntaxKind.InferKeyword, SyntaxKind.IntoKeyword, SyntaxKind.IsFalseKeyword, SyntaxKind.IsTrueKeyword, SyntaxKind.JoinKeyword, SyntaxKind.KeyKeyword, SyntaxKind.MidKeyword, SyntaxKind.OffKeyword, SyntaxKind.OrderKeyword, SyntaxKind.PreserveKeyword, SyntaxKind.RegionKeyword, SyntaxKind.ReferenceKeyword, SyntaxKind.SkipKeyword, SyntaxKind.StrictKeyword, SyntaxKind.TextKeyword, SyntaxKind.TakeKeyword, SyntaxKind.UnicodeKeyword, SyntaxKind.UntilKeyword, SyntaxKind.WarningKeyword, SyntaxKind.WhereKeyword ' These are identifiers that have a contextual kind Return SyntaxFactory.MissingIdentifier(kind) Case SyntaxKind.ExclamationToken, SyntaxKind.CommaToken, SyntaxKind.HashToken, SyntaxKind.AmpersandToken, SyntaxKind.SingleQuoteToken, SyntaxKind.OpenParenToken, SyntaxKind.CloseParenToken, SyntaxKind.OpenBraceToken, SyntaxKind.CloseBraceToken, SyntaxKind.DoubleQuoteToken, SyntaxKind.SemicolonToken, SyntaxKind.AsteriskToken, SyntaxKind.PlusToken, SyntaxKind.MinusToken, SyntaxKind.DotToken, SyntaxKind.SlashToken, SyntaxKind.ColonToken, SyntaxKind.LessThanToken, SyntaxKind.LessThanEqualsToken, SyntaxKind.LessThanGreaterThanToken, SyntaxKind.EqualsToken, SyntaxKind.GreaterThanToken, SyntaxKind.GreaterThanEqualsToken, SyntaxKind.BackslashToken, SyntaxKind.CaretToken, SyntaxKind.ColonEqualsToken, SyntaxKind.AmpersandEqualsToken, SyntaxKind.AsteriskEqualsToken, SyntaxKind.PlusEqualsToken, SyntaxKind.MinusEqualsToken, SyntaxKind.SlashEqualsToken, SyntaxKind.BackslashEqualsToken, SyntaxKind.CaretEqualsToken, SyntaxKind.LessThanLessThanToken, SyntaxKind.GreaterThanGreaterThanToken, SyntaxKind.LessThanLessThanEqualsToken, SyntaxKind.GreaterThanGreaterThanEqualsToken, SyntaxKind.QuestionToken t = SyntaxFactory.MissingPunctuation(kind) Case SyntaxKind.FloatingLiteralToken t = SyntaxFactory.FloatingLiteralToken("", TypeCharacter.None, Nothing, Nothing, Nothing) Case SyntaxKind.DecimalLiteralToken t = SyntaxFactory.DecimalLiteralToken("", TypeCharacter.None, Nothing, Nothing, Nothing) Case SyntaxKind.DateLiteralToken t = SyntaxFactory.DateLiteralToken("", Nothing, Nothing, Nothing) Case SyntaxKind.XmlNameToken t = SyntaxFactory.XmlNameToken("", SyntaxKind.XmlNameToken, Nothing, Nothing) Case SyntaxKind.XmlTextLiteralToken t = SyntaxFactory.XmlTextLiteralToken("", "", Nothing, Nothing) Case SyntaxKind.SlashGreaterThanToken, SyntaxKind.LessThanSlashToken, SyntaxKind.LessThanExclamationMinusMinusToken, SyntaxKind.MinusMinusGreaterThanToken, SyntaxKind.LessThanQuestionToken, SyntaxKind.QuestionGreaterThanToken, SyntaxKind.LessThanPercentEqualsToken, SyntaxKind.PercentGreaterThanToken, SyntaxKind.BeginCDataToken, SyntaxKind.EndCDataToken t = SyntaxFactory.MissingPunctuation(kind) Case SyntaxKind.IdentifierToken t = SyntaxFactory.MissingIdentifier() Case SyntaxKind.IntegerLiteralToken t = MissingIntegerLiteralToken() Case SyntaxKind.StringLiteralToken t = SyntaxFactory.MissingStringLiteral() Case SyntaxKind.CharacterLiteralToken t = SyntaxFactory.MissingCharacterLiteralToken() Case SyntaxKind.InterpolatedStringTextToken t = SyntaxFactory.InterpolatedStringTextToken("", "", Nothing, Nothing) Case Else Throw ExceptionUtilities.UnexpectedValue(kind) End Select Return t End Function Friend Shared Function BadToken(SubKind As SyntaxSubKind, text As String, precedingTrivia As GreenNode, followingTrivia As GreenNode) As BadTokenSyntax Return New BadTokenSyntax(SyntaxKind.BadToken, SubKind, Nothing, Nothing, text, precedingTrivia, followingTrivia) End Function ''' <summary> ''' Create an end-of-text token. ''' </summary> Friend Shared Function EndOfFileToken(precedingTrivia As SyntaxTrivia) As PunctuationSyntax Return New PunctuationSyntax(SyntaxKind.EndOfFileToken, "", precedingTrivia, Nothing) End Function ''' <summary> ''' Create an end-of-text token. ''' </summary> Friend Shared Function EndOfFileToken() As PunctuationSyntax Return New PunctuationSyntax(SyntaxKind.EndOfFileToken, "", Nothing, Nothing) End Function Friend Shared Function Identifier(text As String, isBracketed As Boolean, baseText As String, typeCharacter As TypeCharacter, precedingTrivia As GreenNode, followingTrivia As GreenNode) As IdentifierTokenSyntax Debug.Assert(text IsNot Nothing) Return New ComplexIdentifierSyntax(SyntaxKind.IdentifierToken, Nothing, Nothing, text, precedingTrivia, followingTrivia, SyntaxKind.IdentifierToken, isBracketed, baseText, typeCharacter) End Function Private Shared s_notMissingEmptyToken As PunctuationSyntax = Nothing Friend Shared ReadOnly Property NotMissingEmptyToken() As PunctuationSyntax Get If s_notMissingEmptyToken Is Nothing Then s_notMissingEmptyToken = New PunctuationSyntax(SyntaxKind.EmptyToken, "", Nothing, Nothing) End If Return s_notMissingEmptyToken End Get End Property Private Shared s_missingEmptyToken As PunctuationSyntax = Nothing Friend Shared ReadOnly Property MissingEmptyToken() As PunctuationSyntax Get If s_missingEmptyToken Is Nothing Then s_missingEmptyToken = New PunctuationSyntax(SyntaxKind.EmptyToken, "", Nothing, Nothing) s_missingEmptyToken.ClearFlags(GreenNode.NodeFlags.IsNotMissing) End If Return s_missingEmptyToken End Get End Property Private Shared s_statementTerminatorToken As PunctuationSyntax = Nothing Friend Shared ReadOnly Property StatementTerminatorToken() As PunctuationSyntax Get If s_statementTerminatorToken Is Nothing Then s_statementTerminatorToken = New PunctuationSyntax(SyntaxKind.StatementTerminatorToken, "", Nothing, Nothing) s_statementTerminatorToken.SetFlags(GreenNode.NodeFlags.IsNotMissing) End If Return s_statementTerminatorToken End Get End Property Private Shared s_colonToken As PunctuationSyntax = Nothing Friend Shared ReadOnly Property ColonToken() As PunctuationSyntax Get If s_colonToken Is Nothing Then s_colonToken = New PunctuationSyntax(SyntaxKind.ColonToken, "", Nothing, Nothing) s_colonToken.SetFlags(GreenNode.NodeFlags.IsNotMissing) End If Return s_colonToken End Get End Property Private Shared ReadOnly s_missingExpr As ExpressionSyntax = SyntaxFactory.IdentifierName(SyntaxFactory.Identifier("", Nothing, Nothing)) Friend Shared Function MissingExpression() As ExpressionSyntax Return s_missingExpr End Function Private Shared ReadOnly s_emptyStatement As EmptyStatementSyntax = SyntaxFactory.EmptyStatement(NotMissingEmptyToken) Friend Shared Function EmptyStatement() As EmptyStatementSyntax Return s_emptyStatement End Function Private Shared ReadOnly s_omittedArgument As OmittedArgumentSyntax = SyntaxFactory.OmittedArgument(NotMissingEmptyToken) Friend Shared Function OmittedArgument() As OmittedArgumentSyntax Return s_omittedArgument End Function Public Shared Function TypeBlock(ByVal blockKind As SyntaxKind, ByVal begin As TypeStatementSyntax, ByVal [inherits] As CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of InheritsStatementSyntax), ByVal [implements] As CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of ImplementsStatementSyntax), ByVal members As CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of StatementSyntax), ByVal [end] As EndBlockStatementSyntax) As TypeBlockSyntax Select Case blockKind Case SyntaxKind.ModuleBlock Return SyntaxFactory.ModuleBlock(DirectCast(begin, ModuleStatementSyntax), [inherits], [implements], members, [end]) Case SyntaxKind.ClassBlock Return SyntaxFactory.ClassBlock(DirectCast(begin, ClassStatementSyntax), [inherits], [implements], members, [end]) Case SyntaxKind.StructureBlock Return SyntaxFactory.StructureBlock(DirectCast(begin, StructureStatementSyntax), [inherits], [implements], members, [end]) Case SyntaxKind.InterfaceBlock Return SyntaxFactory.InterfaceBlock(DirectCast(begin, InterfaceStatementSyntax), [inherits], [implements], members, [end]) Case Else Throw ExceptionUtilities.UnexpectedValue(blockKind) End Select End Function Public Shared Function TypeStatement(ByVal statementKind As SyntaxKind, ByVal attributes As CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of GreenNode), ByVal modifiers As CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of GreenNode), ByVal keyword As KeywordSyntax, ByVal identifier As IdentifierTokenSyntax, ByVal typeParameterList As TypeParameterListSyntax) As TypeStatementSyntax Select Case statementKind Case SyntaxKind.ModuleStatement Return SyntaxFactory.ModuleStatement(attributes, modifiers, keyword, identifier, typeParameterList) Case SyntaxKind.ClassStatement Return SyntaxFactory.ClassStatement(attributes, modifiers, keyword, identifier, typeParameterList) Case SyntaxKind.StructureStatement Return SyntaxFactory.StructureStatement(attributes, modifiers, keyword, identifier, typeParameterList) Case SyntaxKind.InterfaceStatement Return SyntaxFactory.InterfaceStatement(attributes, modifiers, keyword, identifier, typeParameterList) Case Else Throw ExceptionUtilities.UnexpectedValue(statementKind) End Select End Function End Class End Namespace
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/ImportDebugInfoTests.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.Reflection Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.CodeGen Imports Microsoft.CodeAnalysis.Debugging Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests Imports Roslyn.Test.Utilities Imports Roslyn.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.UnitTests Public Class ImportsDebugInfoTests Inherits ExpressionCompilerTestBase #Region "Import strings" <Fact> Public Sub SimplestCase() Dim source = " Imports System Class C Sub M() End Sub End Class " Dim comp = CreateCompilationWithMscorlib40({source}, options:=TestOptions.ReleaseDll) WithRuntimeInstance(comp, Sub(runtime) Dim info = GetMethodDebugInfo(runtime, "C.M") If runtime.DebugFormat = DebugInformationFormat.PortablePdb Then info.ImportRecordGroups.Verify(" { Namespace: string='System' } { }") Else info.ImportRecordGroups.Verify(" { Namespace: string='System' CurrentNamespace: string='' } { }") End If End Sub) End Sub <Fact> Public Sub Forward() Dim source = " Imports System.IO Class C ' One of these methods will forward to the other since they're adjacent. Sub M1() End Sub Sub M2() End Sub End Class " Dim comp = CreateCompilationWithMscorlib40({source}, options:=TestOptions.ReleaseDll) WithRuntimeInstance(comp, Sub(runtime) Dim info1 = GetMethodDebugInfo(runtime, "C.M1") If runtime.DebugFormat = DebugInformationFormat.PortablePdb Then info1.ImportRecordGroups.Verify(" { Namespace: string='System.IO' } { }") Else info1.ImportRecordGroups.Verify(" { Namespace: string='System.IO' CurrentNamespace: string='' } { }") End If Assert.Equal("", info1.DefaultNamespaceName) Dim info2 = GetMethodDebugInfo(runtime, "C.M2") If runtime.DebugFormat = DebugInformationFormat.PortablePdb Then info2.ImportRecordGroups.Verify(" { Namespace: string='System.IO' } { }") Else info2.ImportRecordGroups.Verify(" { Namespace: string='System.IO' CurrentNamespace: string='' } { }") End If Assert.Equal("", info2.DefaultNamespaceName) End Sub) End Sub <Fact> Public Sub ImportKinds() Dim source = " Imports System Imports System.IO.Path Imports A = System.Collections Imports B = System.Collections.ArrayList Imports <xmlns=""http://xml0""> Imports <xmlns:C=""http://xml1""> Namespace N Class C Sub M() End Sub End Class End Namespace " Dim options As VisualBasicCompilationOptions = TestOptions.ReleaseDll.WithRootNamespace("root").WithGlobalImports(GlobalImport.Parse( { "System.Runtime", "System.Threading.Thread", "D=System.Threading.Tasks", "E=System.Threading.Timer", "<xmlns=""http://xml2"">", "<xmlns:F=""http://xml3"">" })) Dim comp = CreateCompilationWithMscorlib40({source}, options:=options) WithRuntimeInstance(comp, Sub(runtime) Dim info = GetMethodDebugInfo(runtime, "root.N.C.M") If runtime.DebugFormat = DebugInformationFormat.PortablePdb Then info.ImportRecordGroups.Verify(" { XmlNamespace: alias='' string='http://xml0' XmlNamespace: alias='C' string='http://xml1' Namespace: alias='A' string='System.Collections' Type: alias='B' type='System.Collections.ArrayList' Namespace: string='System' Type: type='System.IO.Path' } { XmlNamespace: alias='' string='http://xml2' XmlNamespace: alias='F' string='http://xml3' Namespace: alias='D' string='System.Threading.Tasks' Type: alias='E' type='System.Threading.Timer' Namespace: string='System.Runtime' Type: type='System.Threading.Thread' }") Else info.ImportRecordGroups.Verify(" { XmlNamespace: alias='' string='http://xml0' XmlNamespace: alias='C' string='http://xml1' NamespaceOrType: alias='A' string='System.Collections' NamespaceOrType: alias='B' string='System.Collections.ArrayList' Namespace: string='System' Type: string='System.IO.Path' CurrentNamespace: string='root.N' } { XmlNamespace: alias='' string='http://xml2' XmlNamespace: alias='F' string='http://xml3' NamespaceOrType: alias='D' string='System.Threading.Tasks' NamespaceOrType: alias='E' string='System.Threading.Timer' Namespace: string='System.Runtime' Type: string='System.Threading.Thread' }") End If Assert.Equal("root", info.DefaultNamespaceName) End Sub) End Sub #End Region #Region "Invalid PDBs" <Fact> Public Sub BadPdb_ForwardChain() Const methodToken1 = &H600057A ' Forwards to 2 Const methodToken2 = &H600055D ' Forwards to 3 Const methodToken3 = &H6000540 ' Has an import Const importString = "@F:System" Dim getMethodImportStrings = Function(token As Integer, arg As Integer) Select Case token Case methodToken1 Return ImmutableArray.Create("@" & methodToken2) Case methodToken2 Return ImmutableArray.Create("@" & methodToken3) Case methodToken3 Return ImmutableArray.Create(importString) Case Else Throw ExceptionUtilities.Unreachable End Select End Function Dim importStrings = CustomDebugInfoReader.GetVisualBasicImportStrings(methodToken1, 0, getMethodImportStrings) Assert.Equal("@" & methodToken3, importStrings.Single()) importStrings = CustomDebugInfoReader.GetVisualBasicImportStrings(methodToken2, 0, getMethodImportStrings) Assert.Equal(importString, importStrings.Single()) importStrings = CustomDebugInfoReader.GetVisualBasicImportStrings(methodToken3, 0, getMethodImportStrings) Assert.Equal(importString, importStrings.Single()) End Sub <Fact> Public Sub BadPdb_ForwardCycle() Const methodToken1 = &H600057A ' Forwards to itself Dim getMethodImportStrings = Function(token As Integer, arg As Integer) Select Case token Case methodToken1 Return ImmutableArray.Create("@" & methodToken1) Case Else Throw ExceptionUtilities.Unreachable End Select End Function Dim importStrings = CustomDebugInfoReader.GetVisualBasicImportStrings(methodToken1, 0, getMethodImportStrings) Assert.Equal("@" & methodToken1, importStrings.Single()) End Sub <WorkItem(999086, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/999086")> <Fact> Public Sub BadPdb_InvalidAliasTarget() Const source = " Public Class C Public Shared Sub Main() End Sub End Class " Dim comp = CreateCompilationWithMscorlib40({source}) Dim exeBytes = comp.EmitToArray() Dim symReader = ExpressionCompilerTestHelpers.ConstructSymReaderWithImports( exeBytes, "Main", "@F:System", ' Valid "@FA:O=1", ' Invalid "@FA:SC=System.Collections") ' Valid Dim exeModule = ModuleInstance.Create(exeBytes, symReader) Dim runtime = CreateRuntimeInstance(exeModule, {MscorlibRef}) Dim evalContext = CreateMethodContext(runtime, "C.Main") Dim compContext = evalContext.CreateCompilationContext(withSyntax:=True) ' Used to throw. Dim rootNamespace As NamespaceSymbol = Nothing Dim currentNamespace As NamespaceSymbol = Nothing Dim typesAndNamespaces As ImmutableArray(Of NamespaceOrTypeAndImportsClausePosition) = Nothing Dim aliases As Dictionary(Of String, AliasAndImportsClausePosition) = Nothing Dim xmlNamespaces As Dictionary(Of String, XmlNamespaceAndImportsClausePosition) = Nothing GetImports(compContext, rootNamespace, currentNamespace, typesAndNamespaces, aliases, xmlNamespaces) Assert.Equal("System", typesAndNamespaces.Single().NamespaceOrType.ToTestDisplayString()) Assert.Equal("SC", aliases.Keys.Single()) End Sub <WorkItem(999086, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/999086")> <Fact> Public Sub BadPdb_InvalidAliasName() Const source = " Public Class C Public Shared Sub Main() End Sub End Class " Dim comp = CreateCompilationWithMscorlib40({source}) Dim exeBytes = comp.EmitToArray() Dim symReader = ExpressionCompilerTestHelpers.ConstructSymReaderWithImports( exeBytes, "Main", "@F:System", ' Valid "@FA:S.I=System.IO", ' Invalid "@FA:SC=System.Collections") ' Valid Dim exeModule = ModuleInstance.Create(exeBytes, symReader) Dim runtime = CreateRuntimeInstance(exeModule, {MscorlibRef}) Dim evalContext = CreateMethodContext(runtime, "C.Main") Dim compContext = evalContext.CreateCompilationContext(withSyntax:=True) ' Used to throw. Dim rootNamespace As NamespaceSymbol = Nothing Dim currentNamespace As NamespaceSymbol = Nothing Dim typesAndNamespaces As ImmutableArray(Of NamespaceOrTypeAndImportsClausePosition) = Nothing Dim aliases As Dictionary(Of String, AliasAndImportsClausePosition) = Nothing Dim xmlNamespaces As Dictionary(Of String, XmlNamespaceAndImportsClausePosition) = Nothing GetImports(compContext, rootNamespace, currentNamespace, typesAndNamespaces, aliases, xmlNamespaces) Assert.Equal("System", typesAndNamespaces.Single().NamespaceOrType.ToTestDisplayString()) Assert.Equal("SC", aliases.Keys.Single()) End Sub <Fact> Public Sub OldPdb_EmbeddedPIA() Const methodToken = &H6000540 ' Has an import Const importString = "&MyPia" Dim getMethodImportStrings = Function(token As Integer, arg As Integer) Select Case token Case methodToken Return ImmutableArray.Create(importString) Case Else Throw ExceptionUtilities.Unreachable End Select End Function Dim importStrings = CustomDebugInfoReader.GetVisualBasicImportStrings(methodToken, 0, getMethodImportStrings) Assert.Equal(importString, importStrings.Single()) End Sub <Fact> Public Sub OldPdb_DefunctKinds() Const methodToken = &H6000540 ' Has an import Const importString1 = "#NotSureWhatGoesHere" Const importString2 = "$NotSureWhatGoesHere" Dim getMethodImportStrings = Function(token As Integer, arg As Integer) Select Case token Case methodToken Return ImmutableArray.Create(importString1, importString2) Case Else Throw ExceptionUtilities.Unreachable End Select End Function Dim importStrings = CustomDebugInfoReader.GetVisualBasicImportStrings(methodToken, 0, getMethodImportStrings) AssertEx.Equal(importStrings, {importString1, importString2}) End Sub #End Region #Region "Binder chain" <Fact> Public Sub ImportKindSymbols() Dim source = " Imports System Imports System.IO.Path Imports A = System.Collections Imports B = System.Collections.ArrayList Imports <xmlns=""http://xml0""> Imports <xmlns:C=""http://xml1""> Namespace N Class C Sub M() Console.WriteLine() End Sub End Class End Namespace " Dim options As VisualBasicCompilationOptions = TestOptions.ReleaseDll.WithRootNamespace("root").WithGlobalImports(GlobalImport.Parse( { "System.Runtime", "System.Threading.Thread", "D=System.Threading.Tasks", "E=System.Threading.Timer", "<xmlns=""http://xml2"">", "<xmlns:F=""http://xml3"">" })) Dim comp = CreateCompilationWithMscorlib40({source}, options:=options) WithRuntimeInstance(comp, Sub(runtime) Dim info = GetMethodDebugInfo(runtime, "root.N.C.M") If runtime.DebugFormat = DebugInformationFormat.PortablePdb Then info.ImportRecordGroups.Verify(" { XmlNamespace: alias='' string='http://xml0' XmlNamespace: alias='C' string='http://xml1' Namespace: alias='A' string='System.Collections' Type: alias='B' type='System.Collections.ArrayList' Namespace: string='System' Type: type='System.IO.Path' } { XmlNamespace: alias='' string='http://xml2' XmlNamespace: alias='F' string='http://xml3' Namespace: alias='D' string='System.Threading.Tasks' Type: alias='E' type='System.Threading.Timer' Namespace: string='System.Runtime' Type: type='System.Threading.Thread' }") Else info.ImportRecordGroups.Verify(" { XmlNamespace: alias='' string='http://xml0' XmlNamespace: alias='C' string='http://xml1' NamespaceOrType: alias='A' string='System.Collections' NamespaceOrType: alias='B' string='System.Collections.ArrayList' Namespace: string='System' Type: string='System.IO.Path' CurrentNamespace: string='root.N' } { XmlNamespace: alias='' string='http://xml2' XmlNamespace: alias='F' string='http://xml3' NamespaceOrType: alias='D' string='System.Threading.Tasks' NamespaceOrType: alias='E' string='System.Threading.Timer' Namespace: string='System.Runtime' Type: string='System.Threading.Thread' }") End If Dim rootNamespace As NamespaceSymbol = Nothing Dim currentNamespace As NamespaceSymbol = Nothing Dim typesAndNamespaces As ImmutableArray(Of NamespaceOrTypeAndImportsClausePosition) = Nothing Dim aliases As Dictionary(Of String, AliasAndImportsClausePosition) = Nothing Dim xmlNamespaces As Dictionary(Of String, XmlNamespaceAndImportsClausePosition) = Nothing GetImports( runtime, "root.N.C.M", rootNamespace, currentNamespace, typesAndNamespaces, aliases, xmlNamespaces) Assert.Equal("root", rootNamespace.ToTestDisplayString()) Assert.Equal("root.N", currentNamespace.ToTestDisplayString()) Dim expectedNamespaces = If(runtime.DebugFormat = DebugInformationFormat.PortablePdb, {"System", "System.IO.Path", "System.Runtime", "System.Threading.Thread"}, {"System", "System.IO.Path", "System.Runtime", "System.Threading.Thread", "root.N"}) AssertEx.SetEqual(expectedNamespaces, typesAndNamespaces.Select(Function(i) i.NamespaceOrType.ToTestDisplayString())) AssertEx.SetEqual(aliases.Keys, "A", "B", "D", "E") Assert.Equal("System.Collections", aliases("A").Alias.Target.ToTestDisplayString()) Assert.Equal("System.Collections.ArrayList", aliases("B").Alias.Target.ToTestDisplayString()) Assert.Equal("System.Threading.Tasks", aliases("D").Alias.Target.ToTestDisplayString()) Assert.Equal("System.Threading.Timer", aliases("E").Alias.Target.ToTestDisplayString()) AssertEx.SetEqual(xmlNamespaces.Keys, "", "C", "F") Assert.Equal("http://xml0", xmlNamespaces("").XmlNamespace) Assert.Equal("http://xml1", xmlNamespaces("C").XmlNamespace) Assert.Equal("http://xml3", xmlNamespaces("F").XmlNamespace) End Sub) End Sub <Fact> Public Sub EmptyRootNamespace() Dim source = " Namespace N Class C Sub M() System.Console.WriteLine() End Sub End Class End Namespace " For Each rootNamespaceName In {"", Nothing} Dim comp = CreateCompilationWithMscorlib40({source}, options:=TestOptions.ReleaseDll.WithRootNamespace(rootNamespaceName)) comp.GetDiagnostics().Where(Function(d) d.Severity > DiagnosticSeverity.Info).Verify() WithRuntimeInstance(comp, Sub(runtime) Dim rootNamespace As NamespaceSymbol = Nothing Dim currentNamespace As NamespaceSymbol = Nothing Dim typesAndNamespaces As ImmutableArray(Of NamespaceOrTypeAndImportsClausePosition) = Nothing Dim aliases As Dictionary(Of String, AliasAndImportsClausePosition) = Nothing Dim xmlNamespaces As Dictionary(Of String, XmlNamespaceAndImportsClausePosition) = Nothing GetImports( runtime, "N.C.M", rootNamespace, currentNamespace, typesAndNamespaces, aliases, xmlNamespaces) Assert.True(rootNamespace.IsGlobalNamespace) Assert.Equal("N", currentNamespace.ToTestDisplayString()) ' Portable PDB doesn't include CurrentNamespace: If runtime.DebugFormat = DebugInformationFormat.PortablePdb Then Assert.True(typesAndNamespaces.IsDefault) Else Assert.Equal("N", typesAndNamespaces.Single().NamespaceOrType.ToTestDisplayString()) End If Assert.Null(aliases) Assert.Null(xmlNamespaces) End Sub) Next End Sub <Fact> Public Sub TieBreaking() Dim source = " Imports System Imports System.IO.Path Imports A = System.Collections Imports B = System.Collections.ArrayList Imports <xmlns=""http://xml0""> Imports <xmlns:C=""http://xml1""> Namespace N Class C Sub M() Console.WriteLine() End Sub End Class End Namespace " Dim options As VisualBasicCompilationOptions = TestOptions.ReleaseDll.WithRootNamespace("root").WithGlobalImports(GlobalImport.Parse( { "System", "System.IO.Path", "A=System.Threading.Tasks", "B=System.Threading.Timer", "<xmlns=""http://xml2"">", "<xmlns:C=""http://xml3"">" })) Dim comp = CreateCompilationWithMscorlib40({source}, options:=options) comp.GetDiagnostics().Where(Function(d) d.Severity > DiagnosticSeverity.Info).Verify() Dim rootNamespace As NamespaceSymbol = Nothing Dim currentNamespace As NamespaceSymbol = Nothing Dim typesAndNamespaces As ImmutableArray(Of NamespaceOrTypeAndImportsClausePosition) = Nothing Dim aliases As Dictionary(Of String, AliasAndImportsClausePosition) = Nothing Dim xmlNamespaces As Dictionary(Of String, XmlNamespaceAndImportsClausePosition) = Nothing WithRuntimeInstance(comp, Sub(runtime) GetImports( runtime, "root.N.C.M", rootNamespace, currentNamespace, typesAndNamespaces, aliases, xmlNamespaces) Assert.Equal("root", rootNamespace.ToTestDisplayString()) Assert.Equal("root.N", currentNamespace.ToTestDisplayString()) ' CONSIDER: We could de-dup unaliased imports as well. Dim expectedNamespaces = If(runtime.DebugFormat = DebugInformationFormat.PortablePdb, {"System", "System.IO.Path", "System", "System.IO.Path"}, {"System", "System.IO.Path", "System", "System.IO.Path", "root.N"}) AssertEx.SetEqual(expectedNamespaces, typesAndNamespaces.Select(Function(i) i.NamespaceOrType.ToTestDisplayString())) AssertEx.SetEqual(aliases.Keys, "A", "B") Assert.Equal("System.Collections", aliases("A").Alias.Target.ToTestDisplayString()) Assert.Equal("System.Collections.ArrayList", aliases("B").Alias.Target.ToTestDisplayString()) AssertEx.SetEqual(xmlNamespaces.Keys, "", "C") Assert.Equal("http://xml0", xmlNamespaces("").XmlNamespace) Assert.Equal("http://xml1", xmlNamespaces("C").XmlNamespace) End Sub) End Sub <WorkItem(2441, "https://github.com/dotnet/roslyn/issues/2441")> <Fact> Public Sub AssemblyQualifiedNameResolutionWithUnification() Const source1 = " Imports SI = System.Int32 Public Class C1 Sub M() End Sub End Class " Const source2 = " Public Class C2 : Inherits C1 End Class " Dim comp1 = CreateEmptyCompilationWithReferences(VisualBasicSyntaxTree.ParseText(source1), {MscorlibRef_v20}, TestOptions.DebugDll) Dim module1 = comp1.ToModuleInstance() Dim comp2 = CreateEmptyCompilationWithReferences(VisualBasicSyntaxTree.ParseText(source2), {MscorlibRef_v4_0_30316_17626, module1.GetReference()}, TestOptions.DebugDll) Dim module2 = comp2.ToModuleInstance() Dim runtime = CreateRuntimeInstance({module1, module2, MscorlibRef_v4_0_30316_17626.ToModuleInstance(), ExpressionCompilerTestHelpers.IntrinsicAssemblyReference.ToModuleInstance()}) Dim context = CreateMethodContext(runtime, "C1.M") Dim errorMessage As String = Nothing Dim testData As New CompilationTestData() context.CompileExpression("GetType(SI)", errorMessage, testData) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL(" { // Code size 11 (0xb) .maxstack 1 IL_0000: ldtoken ""Integer"" IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type"" IL_000a: ret } ") End Sub Private Shared Sub GetImports( runtime As RuntimeInstance, methodName As String, <Out> ByRef rootNamespace As NamespaceSymbol, <Out> ByRef currentNamespace As NamespaceSymbol, <Out> ByRef typesAndNamespaces As ImmutableArray(Of NamespaceOrTypeAndImportsClausePosition), <Out> ByRef aliases As Dictionary(Of String, AliasAndImportsClausePosition), <Out> ByRef xmlNamespaces As Dictionary(Of String, XmlNamespaceAndImportsClausePosition)) Dim evalContext = CreateMethodContext(runtime, methodName) Dim compContext = evalContext.CreateCompilationContext(withSyntax:=True) GetImports(compContext, rootNamespace, currentNamespace, typesAndNamespaces, aliases, xmlNamespaces) End Sub Friend Shared Sub GetImports( compContext As CompilationContext, <Out> ByRef rootNamespace As NamespaceSymbol, <Out> ByRef currentNamespace As NamespaceSymbol, <Out> ByRef typesAndNamespaces As ImmutableArray(Of NamespaceOrTypeAndImportsClausePosition), <Out> ByRef aliases As Dictionary(Of String, AliasAndImportsClausePosition), <Out> ByRef xmlNamespaces As Dictionary(Of String, XmlNamespaceAndImportsClausePosition)) Dim binder = compContext.NamespaceBinder Assert.NotNull(binder) rootNamespace = compContext.Compilation.RootNamespace Dim containing = binder.ContainingNamespaceOrType Assert.NotNull(containing) currentNamespace = If(containing.Kind = SymbolKind.Namespace, DirectCast(containing, NamespaceSymbol), containing.ContainingNamespace) typesAndNamespaces = Nothing aliases = Nothing xmlNamespaces = Nothing Const bindingFlags As BindingFlags = BindingFlags.NonPublic Or BindingFlags.Instance Dim typesAndNamespacesField = GetType(ImportedTypesAndNamespacesMembersBinder).GetField("_importedSymbols", bindingFlags) Assert.NotNull(typesAndNamespacesField) Dim aliasesField = GetType(ImportAliasesBinder).GetField("_importedAliases", bindingFlags) Assert.NotNull(aliasesField) Dim xmlNamespacesField = GetType(XmlNamespaceImportsBinder).GetField("_namespaces", bindingFlags) Assert.NotNull(xmlNamespacesField) While binder IsNot Nothing If TypeOf binder Is ImportedTypesAndNamespacesMembersBinder Then Assert.True(typesAndNamespaces.IsDefault) typesAndNamespaces = DirectCast(typesAndNamespacesField.GetValue(binder), ImmutableArray(Of NamespaceOrTypeAndImportsClausePosition)) AssertEx.None(typesAndNamespaces, Function(tOrN) tOrN.NamespaceOrType.Kind = SymbolKind.ErrorType) Assert.False(typesAndNamespaces.IsDefault) ElseIf TypeOf binder Is ImportAliasesBinder Then Assert.Null(aliases) aliases = DirectCast(aliasesField.GetValue(binder), Dictionary(Of String, AliasAndImportsClausePosition)) AssertEx.All(aliases, Function(pair) pair.Key = pair.Value.Alias.Name) Assert.NotNull(aliases) ElseIf TypeOf binder Is XmlNamespaceImportsBinder Then Assert.Null(xmlNamespaces) xmlNamespaces = DirectCast(xmlNamespacesField.GetValue(binder), Dictionary(Of String, XmlNamespaceAndImportsClausePosition)) Assert.NotNull(xmlNamespaces) End If binder = binder.ContainingBinder End While 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 System.Collections.Immutable Imports System.Reflection Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.CodeGen Imports Microsoft.CodeAnalysis.Debugging Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests Imports Roslyn.Test.Utilities Imports Roslyn.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.UnitTests Public Class ImportsDebugInfoTests Inherits ExpressionCompilerTestBase #Region "Import strings" <Fact> Public Sub SimplestCase() Dim source = " Imports System Class C Sub M() End Sub End Class " Dim comp = CreateCompilationWithMscorlib40({source}, options:=TestOptions.ReleaseDll) WithRuntimeInstance(comp, Sub(runtime) Dim info = GetMethodDebugInfo(runtime, "C.M") If runtime.DebugFormat = DebugInformationFormat.PortablePdb Then info.ImportRecordGroups.Verify(" { Namespace: string='System' } { }") Else info.ImportRecordGroups.Verify(" { Namespace: string='System' CurrentNamespace: string='' } { }") End If End Sub) End Sub <Fact> Public Sub Forward() Dim source = " Imports System.IO Class C ' One of these methods will forward to the other since they're adjacent. Sub M1() End Sub Sub M2() End Sub End Class " Dim comp = CreateCompilationWithMscorlib40({source}, options:=TestOptions.ReleaseDll) WithRuntimeInstance(comp, Sub(runtime) Dim info1 = GetMethodDebugInfo(runtime, "C.M1") If runtime.DebugFormat = DebugInformationFormat.PortablePdb Then info1.ImportRecordGroups.Verify(" { Namespace: string='System.IO' } { }") Else info1.ImportRecordGroups.Verify(" { Namespace: string='System.IO' CurrentNamespace: string='' } { }") End If Assert.Equal("", info1.DefaultNamespaceName) Dim info2 = GetMethodDebugInfo(runtime, "C.M2") If runtime.DebugFormat = DebugInformationFormat.PortablePdb Then info2.ImportRecordGroups.Verify(" { Namespace: string='System.IO' } { }") Else info2.ImportRecordGroups.Verify(" { Namespace: string='System.IO' CurrentNamespace: string='' } { }") End If Assert.Equal("", info2.DefaultNamespaceName) End Sub) End Sub <Fact> Public Sub ImportKinds() Dim source = " Imports System Imports System.IO.Path Imports A = System.Collections Imports B = System.Collections.ArrayList Imports <xmlns=""http://xml0""> Imports <xmlns:C=""http://xml1""> Namespace N Class C Sub M() End Sub End Class End Namespace " Dim options As VisualBasicCompilationOptions = TestOptions.ReleaseDll.WithRootNamespace("root").WithGlobalImports(GlobalImport.Parse( { "System.Runtime", "System.Threading.Thread", "D=System.Threading.Tasks", "E=System.Threading.Timer", "<xmlns=""http://xml2"">", "<xmlns:F=""http://xml3"">" })) Dim comp = CreateCompilationWithMscorlib40({source}, options:=options) WithRuntimeInstance(comp, Sub(runtime) Dim info = GetMethodDebugInfo(runtime, "root.N.C.M") If runtime.DebugFormat = DebugInformationFormat.PortablePdb Then info.ImportRecordGroups.Verify(" { XmlNamespace: alias='' string='http://xml0' XmlNamespace: alias='C' string='http://xml1' Namespace: alias='A' string='System.Collections' Type: alias='B' type='System.Collections.ArrayList' Namespace: string='System' Type: type='System.IO.Path' } { XmlNamespace: alias='' string='http://xml2' XmlNamespace: alias='F' string='http://xml3' Namespace: alias='D' string='System.Threading.Tasks' Type: alias='E' type='System.Threading.Timer' Namespace: string='System.Runtime' Type: type='System.Threading.Thread' }") Else info.ImportRecordGroups.Verify(" { XmlNamespace: alias='' string='http://xml0' XmlNamespace: alias='C' string='http://xml1' NamespaceOrType: alias='A' string='System.Collections' NamespaceOrType: alias='B' string='System.Collections.ArrayList' Namespace: string='System' Type: string='System.IO.Path' CurrentNamespace: string='root.N' } { XmlNamespace: alias='' string='http://xml2' XmlNamespace: alias='F' string='http://xml3' NamespaceOrType: alias='D' string='System.Threading.Tasks' NamespaceOrType: alias='E' string='System.Threading.Timer' Namespace: string='System.Runtime' Type: string='System.Threading.Thread' }") End If Assert.Equal("root", info.DefaultNamespaceName) End Sub) End Sub #End Region #Region "Invalid PDBs" <Fact> Public Sub BadPdb_ForwardChain() Const methodToken1 = &H600057A ' Forwards to 2 Const methodToken2 = &H600055D ' Forwards to 3 Const methodToken3 = &H6000540 ' Has an import Const importString = "@F:System" Dim getMethodImportStrings = Function(token As Integer, arg As Integer) Select Case token Case methodToken1 Return ImmutableArray.Create("@" & methodToken2) Case methodToken2 Return ImmutableArray.Create("@" & methodToken3) Case methodToken3 Return ImmutableArray.Create(importString) Case Else Throw ExceptionUtilities.Unreachable End Select End Function Dim importStrings = CustomDebugInfoReader.GetVisualBasicImportStrings(methodToken1, 0, getMethodImportStrings) Assert.Equal("@" & methodToken3, importStrings.Single()) importStrings = CustomDebugInfoReader.GetVisualBasicImportStrings(methodToken2, 0, getMethodImportStrings) Assert.Equal(importString, importStrings.Single()) importStrings = CustomDebugInfoReader.GetVisualBasicImportStrings(methodToken3, 0, getMethodImportStrings) Assert.Equal(importString, importStrings.Single()) End Sub <Fact> Public Sub BadPdb_ForwardCycle() Const methodToken1 = &H600057A ' Forwards to itself Dim getMethodImportStrings = Function(token As Integer, arg As Integer) Select Case token Case methodToken1 Return ImmutableArray.Create("@" & methodToken1) Case Else Throw ExceptionUtilities.Unreachable End Select End Function Dim importStrings = CustomDebugInfoReader.GetVisualBasicImportStrings(methodToken1, 0, getMethodImportStrings) Assert.Equal("@" & methodToken1, importStrings.Single()) End Sub <WorkItem(999086, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/999086")> <Fact> Public Sub BadPdb_InvalidAliasTarget() Const source = " Public Class C Public Shared Sub Main() End Sub End Class " Dim comp = CreateCompilationWithMscorlib40({source}) Dim exeBytes = comp.EmitToArray() Dim symReader = ExpressionCompilerTestHelpers.ConstructSymReaderWithImports( exeBytes, "Main", "@F:System", ' Valid "@FA:O=1", ' Invalid "@FA:SC=System.Collections") ' Valid Dim exeModule = ModuleInstance.Create(exeBytes, symReader) Dim runtime = CreateRuntimeInstance(exeModule, {MscorlibRef}) Dim evalContext = CreateMethodContext(runtime, "C.Main") Dim compContext = evalContext.CreateCompilationContext(withSyntax:=True) ' Used to throw. Dim rootNamespace As NamespaceSymbol = Nothing Dim currentNamespace As NamespaceSymbol = Nothing Dim typesAndNamespaces As ImmutableArray(Of NamespaceOrTypeAndImportsClausePosition) = Nothing Dim aliases As Dictionary(Of String, AliasAndImportsClausePosition) = Nothing Dim xmlNamespaces As Dictionary(Of String, XmlNamespaceAndImportsClausePosition) = Nothing GetImports(compContext, rootNamespace, currentNamespace, typesAndNamespaces, aliases, xmlNamespaces) Assert.Equal("System", typesAndNamespaces.Single().NamespaceOrType.ToTestDisplayString()) Assert.Equal("SC", aliases.Keys.Single()) End Sub <WorkItem(999086, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/999086")> <Fact> Public Sub BadPdb_InvalidAliasName() Const source = " Public Class C Public Shared Sub Main() End Sub End Class " Dim comp = CreateCompilationWithMscorlib40({source}) Dim exeBytes = comp.EmitToArray() Dim symReader = ExpressionCompilerTestHelpers.ConstructSymReaderWithImports( exeBytes, "Main", "@F:System", ' Valid "@FA:S.I=System.IO", ' Invalid "@FA:SC=System.Collections") ' Valid Dim exeModule = ModuleInstance.Create(exeBytes, symReader) Dim runtime = CreateRuntimeInstance(exeModule, {MscorlibRef}) Dim evalContext = CreateMethodContext(runtime, "C.Main") Dim compContext = evalContext.CreateCompilationContext(withSyntax:=True) ' Used to throw. Dim rootNamespace As NamespaceSymbol = Nothing Dim currentNamespace As NamespaceSymbol = Nothing Dim typesAndNamespaces As ImmutableArray(Of NamespaceOrTypeAndImportsClausePosition) = Nothing Dim aliases As Dictionary(Of String, AliasAndImportsClausePosition) = Nothing Dim xmlNamespaces As Dictionary(Of String, XmlNamespaceAndImportsClausePosition) = Nothing GetImports(compContext, rootNamespace, currentNamespace, typesAndNamespaces, aliases, xmlNamespaces) Assert.Equal("System", typesAndNamespaces.Single().NamespaceOrType.ToTestDisplayString()) Assert.Equal("SC", aliases.Keys.Single()) End Sub <Fact> Public Sub OldPdb_EmbeddedPIA() Const methodToken = &H6000540 ' Has an import Const importString = "&MyPia" Dim getMethodImportStrings = Function(token As Integer, arg As Integer) Select Case token Case methodToken Return ImmutableArray.Create(importString) Case Else Throw ExceptionUtilities.Unreachable End Select End Function Dim importStrings = CustomDebugInfoReader.GetVisualBasicImportStrings(methodToken, 0, getMethodImportStrings) Assert.Equal(importString, importStrings.Single()) End Sub <Fact> Public Sub OldPdb_DefunctKinds() Const methodToken = &H6000540 ' Has an import Const importString1 = "#NotSureWhatGoesHere" Const importString2 = "$NotSureWhatGoesHere" Dim getMethodImportStrings = Function(token As Integer, arg As Integer) Select Case token Case methodToken Return ImmutableArray.Create(importString1, importString2) Case Else Throw ExceptionUtilities.Unreachable End Select End Function Dim importStrings = CustomDebugInfoReader.GetVisualBasicImportStrings(methodToken, 0, getMethodImportStrings) AssertEx.Equal(importStrings, {importString1, importString2}) End Sub #End Region #Region "Binder chain" <Fact> Public Sub ImportKindSymbols() Dim source = " Imports System Imports System.IO.Path Imports A = System.Collections Imports B = System.Collections.ArrayList Imports <xmlns=""http://xml0""> Imports <xmlns:C=""http://xml1""> Namespace N Class C Sub M() Console.WriteLine() End Sub End Class End Namespace " Dim options As VisualBasicCompilationOptions = TestOptions.ReleaseDll.WithRootNamespace("root").WithGlobalImports(GlobalImport.Parse( { "System.Runtime", "System.Threading.Thread", "D=System.Threading.Tasks", "E=System.Threading.Timer", "<xmlns=""http://xml2"">", "<xmlns:F=""http://xml3"">" })) Dim comp = CreateCompilationWithMscorlib40({source}, options:=options) WithRuntimeInstance(comp, Sub(runtime) Dim info = GetMethodDebugInfo(runtime, "root.N.C.M") If runtime.DebugFormat = DebugInformationFormat.PortablePdb Then info.ImportRecordGroups.Verify(" { XmlNamespace: alias='' string='http://xml0' XmlNamespace: alias='C' string='http://xml1' Namespace: alias='A' string='System.Collections' Type: alias='B' type='System.Collections.ArrayList' Namespace: string='System' Type: type='System.IO.Path' } { XmlNamespace: alias='' string='http://xml2' XmlNamespace: alias='F' string='http://xml3' Namespace: alias='D' string='System.Threading.Tasks' Type: alias='E' type='System.Threading.Timer' Namespace: string='System.Runtime' Type: type='System.Threading.Thread' }") Else info.ImportRecordGroups.Verify(" { XmlNamespace: alias='' string='http://xml0' XmlNamespace: alias='C' string='http://xml1' NamespaceOrType: alias='A' string='System.Collections' NamespaceOrType: alias='B' string='System.Collections.ArrayList' Namespace: string='System' Type: string='System.IO.Path' CurrentNamespace: string='root.N' } { XmlNamespace: alias='' string='http://xml2' XmlNamespace: alias='F' string='http://xml3' NamespaceOrType: alias='D' string='System.Threading.Tasks' NamespaceOrType: alias='E' string='System.Threading.Timer' Namespace: string='System.Runtime' Type: string='System.Threading.Thread' }") End If Dim rootNamespace As NamespaceSymbol = Nothing Dim currentNamespace As NamespaceSymbol = Nothing Dim typesAndNamespaces As ImmutableArray(Of NamespaceOrTypeAndImportsClausePosition) = Nothing Dim aliases As Dictionary(Of String, AliasAndImportsClausePosition) = Nothing Dim xmlNamespaces As Dictionary(Of String, XmlNamespaceAndImportsClausePosition) = Nothing GetImports( runtime, "root.N.C.M", rootNamespace, currentNamespace, typesAndNamespaces, aliases, xmlNamespaces) Assert.Equal("root", rootNamespace.ToTestDisplayString()) Assert.Equal("root.N", currentNamespace.ToTestDisplayString()) Dim expectedNamespaces = If(runtime.DebugFormat = DebugInformationFormat.PortablePdb, {"System", "System.IO.Path", "System.Runtime", "System.Threading.Thread"}, {"System", "System.IO.Path", "System.Runtime", "System.Threading.Thread", "root.N"}) AssertEx.SetEqual(expectedNamespaces, typesAndNamespaces.Select(Function(i) i.NamespaceOrType.ToTestDisplayString())) AssertEx.SetEqual(aliases.Keys, "A", "B", "D", "E") Assert.Equal("System.Collections", aliases("A").Alias.Target.ToTestDisplayString()) Assert.Equal("System.Collections.ArrayList", aliases("B").Alias.Target.ToTestDisplayString()) Assert.Equal("System.Threading.Tasks", aliases("D").Alias.Target.ToTestDisplayString()) Assert.Equal("System.Threading.Timer", aliases("E").Alias.Target.ToTestDisplayString()) AssertEx.SetEqual(xmlNamespaces.Keys, "", "C", "F") Assert.Equal("http://xml0", xmlNamespaces("").XmlNamespace) Assert.Equal("http://xml1", xmlNamespaces("C").XmlNamespace) Assert.Equal("http://xml3", xmlNamespaces("F").XmlNamespace) End Sub) End Sub <Fact> Public Sub EmptyRootNamespace() Dim source = " Namespace N Class C Sub M() System.Console.WriteLine() End Sub End Class End Namespace " For Each rootNamespaceName In {"", Nothing} Dim comp = CreateCompilationWithMscorlib40({source}, options:=TestOptions.ReleaseDll.WithRootNamespace(rootNamespaceName)) comp.GetDiagnostics().Where(Function(d) d.Severity > DiagnosticSeverity.Info).Verify() WithRuntimeInstance(comp, Sub(runtime) Dim rootNamespace As NamespaceSymbol = Nothing Dim currentNamespace As NamespaceSymbol = Nothing Dim typesAndNamespaces As ImmutableArray(Of NamespaceOrTypeAndImportsClausePosition) = Nothing Dim aliases As Dictionary(Of String, AliasAndImportsClausePosition) = Nothing Dim xmlNamespaces As Dictionary(Of String, XmlNamespaceAndImportsClausePosition) = Nothing GetImports( runtime, "N.C.M", rootNamespace, currentNamespace, typesAndNamespaces, aliases, xmlNamespaces) Assert.True(rootNamespace.IsGlobalNamespace) Assert.Equal("N", currentNamespace.ToTestDisplayString()) ' Portable PDB doesn't include CurrentNamespace: If runtime.DebugFormat = DebugInformationFormat.PortablePdb Then Assert.True(typesAndNamespaces.IsDefault) Else Assert.Equal("N", typesAndNamespaces.Single().NamespaceOrType.ToTestDisplayString()) End If Assert.Null(aliases) Assert.Null(xmlNamespaces) End Sub) Next End Sub <Fact> Public Sub TieBreaking() Dim source = " Imports System Imports System.IO.Path Imports A = System.Collections Imports B = System.Collections.ArrayList Imports <xmlns=""http://xml0""> Imports <xmlns:C=""http://xml1""> Namespace N Class C Sub M() Console.WriteLine() End Sub End Class End Namespace " Dim options As VisualBasicCompilationOptions = TestOptions.ReleaseDll.WithRootNamespace("root").WithGlobalImports(GlobalImport.Parse( { "System", "System.IO.Path", "A=System.Threading.Tasks", "B=System.Threading.Timer", "<xmlns=""http://xml2"">", "<xmlns:C=""http://xml3"">" })) Dim comp = CreateCompilationWithMscorlib40({source}, options:=options) comp.GetDiagnostics().Where(Function(d) d.Severity > DiagnosticSeverity.Info).Verify() Dim rootNamespace As NamespaceSymbol = Nothing Dim currentNamespace As NamespaceSymbol = Nothing Dim typesAndNamespaces As ImmutableArray(Of NamespaceOrTypeAndImportsClausePosition) = Nothing Dim aliases As Dictionary(Of String, AliasAndImportsClausePosition) = Nothing Dim xmlNamespaces As Dictionary(Of String, XmlNamespaceAndImportsClausePosition) = Nothing WithRuntimeInstance(comp, Sub(runtime) GetImports( runtime, "root.N.C.M", rootNamespace, currentNamespace, typesAndNamespaces, aliases, xmlNamespaces) Assert.Equal("root", rootNamespace.ToTestDisplayString()) Assert.Equal("root.N", currentNamespace.ToTestDisplayString()) ' CONSIDER: We could de-dup unaliased imports as well. Dim expectedNamespaces = If(runtime.DebugFormat = DebugInformationFormat.PortablePdb, {"System", "System.IO.Path", "System", "System.IO.Path"}, {"System", "System.IO.Path", "System", "System.IO.Path", "root.N"}) AssertEx.SetEqual(expectedNamespaces, typesAndNamespaces.Select(Function(i) i.NamespaceOrType.ToTestDisplayString())) AssertEx.SetEqual(aliases.Keys, "A", "B") Assert.Equal("System.Collections", aliases("A").Alias.Target.ToTestDisplayString()) Assert.Equal("System.Collections.ArrayList", aliases("B").Alias.Target.ToTestDisplayString()) AssertEx.SetEqual(xmlNamespaces.Keys, "", "C") Assert.Equal("http://xml0", xmlNamespaces("").XmlNamespace) Assert.Equal("http://xml1", xmlNamespaces("C").XmlNamespace) End Sub) End Sub <WorkItem(2441, "https://github.com/dotnet/roslyn/issues/2441")> <Fact> Public Sub AssemblyQualifiedNameResolutionWithUnification() Const source1 = " Imports SI = System.Int32 Public Class C1 Sub M() End Sub End Class " Const source2 = " Public Class C2 : Inherits C1 End Class " Dim comp1 = CreateEmptyCompilationWithReferences(VisualBasicSyntaxTree.ParseText(source1), {MscorlibRef_v20}, TestOptions.DebugDll) Dim module1 = comp1.ToModuleInstance() Dim comp2 = CreateEmptyCompilationWithReferences(VisualBasicSyntaxTree.ParseText(source2), {MscorlibRef_v4_0_30316_17626, module1.GetReference()}, TestOptions.DebugDll) Dim module2 = comp2.ToModuleInstance() Dim runtime = CreateRuntimeInstance({module1, module2, MscorlibRef_v4_0_30316_17626.ToModuleInstance(), ExpressionCompilerTestHelpers.IntrinsicAssemblyReference.ToModuleInstance()}) Dim context = CreateMethodContext(runtime, "C1.M") Dim errorMessage As String = Nothing Dim testData As New CompilationTestData() context.CompileExpression("GetType(SI)", errorMessage, testData) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL(" { // Code size 11 (0xb) .maxstack 1 IL_0000: ldtoken ""Integer"" IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type"" IL_000a: ret } ") End Sub Private Shared Sub GetImports( runtime As RuntimeInstance, methodName As String, <Out> ByRef rootNamespace As NamespaceSymbol, <Out> ByRef currentNamespace As NamespaceSymbol, <Out> ByRef typesAndNamespaces As ImmutableArray(Of NamespaceOrTypeAndImportsClausePosition), <Out> ByRef aliases As Dictionary(Of String, AliasAndImportsClausePosition), <Out> ByRef xmlNamespaces As Dictionary(Of String, XmlNamespaceAndImportsClausePosition)) Dim evalContext = CreateMethodContext(runtime, methodName) Dim compContext = evalContext.CreateCompilationContext(withSyntax:=True) GetImports(compContext, rootNamespace, currentNamespace, typesAndNamespaces, aliases, xmlNamespaces) End Sub Friend Shared Sub GetImports( compContext As CompilationContext, <Out> ByRef rootNamespace As NamespaceSymbol, <Out> ByRef currentNamespace As NamespaceSymbol, <Out> ByRef typesAndNamespaces As ImmutableArray(Of NamespaceOrTypeAndImportsClausePosition), <Out> ByRef aliases As Dictionary(Of String, AliasAndImportsClausePosition), <Out> ByRef xmlNamespaces As Dictionary(Of String, XmlNamespaceAndImportsClausePosition)) Dim binder = compContext.NamespaceBinder Assert.NotNull(binder) rootNamespace = compContext.Compilation.RootNamespace Dim containing = binder.ContainingNamespaceOrType Assert.NotNull(containing) currentNamespace = If(containing.Kind = SymbolKind.Namespace, DirectCast(containing, NamespaceSymbol), containing.ContainingNamespace) typesAndNamespaces = Nothing aliases = Nothing xmlNamespaces = Nothing Const bindingFlags As BindingFlags = BindingFlags.NonPublic Or BindingFlags.Instance Dim typesAndNamespacesField = GetType(ImportedTypesAndNamespacesMembersBinder).GetField("_importedSymbols", bindingFlags) Assert.NotNull(typesAndNamespacesField) Dim aliasesField = GetType(ImportAliasesBinder).GetField("_importedAliases", bindingFlags) Assert.NotNull(aliasesField) Dim xmlNamespacesField = GetType(XmlNamespaceImportsBinder).GetField("_namespaces", bindingFlags) Assert.NotNull(xmlNamespacesField) While binder IsNot Nothing If TypeOf binder Is ImportedTypesAndNamespacesMembersBinder Then Assert.True(typesAndNamespaces.IsDefault) typesAndNamespaces = DirectCast(typesAndNamespacesField.GetValue(binder), ImmutableArray(Of NamespaceOrTypeAndImportsClausePosition)) AssertEx.None(typesAndNamespaces, Function(tOrN) tOrN.NamespaceOrType.Kind = SymbolKind.ErrorType) Assert.False(typesAndNamespaces.IsDefault) ElseIf TypeOf binder Is ImportAliasesBinder Then Assert.Null(aliases) aliases = DirectCast(aliasesField.GetValue(binder), Dictionary(Of String, AliasAndImportsClausePosition)) AssertEx.All(aliases, Function(pair) pair.Key = pair.Value.Alias.Name) Assert.NotNull(aliases) ElseIf TypeOf binder Is XmlNamespaceImportsBinder Then Assert.Null(xmlNamespaces) xmlNamespaces = DirectCast(xmlNamespacesField.GetValue(binder), Dictionary(Of String, XmlNamespaceAndImportsClausePosition)) Assert.NotNull(xmlNamespaces) End If binder = binder.ContainingBinder End While End Sub #End Region End Class End Namespace
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/Workspaces/MSBuildTest/Resources/SolutionFiles/InvalidProjectPath.sln
 Microsoft Visual Studio Solution File, Format Version 11.00 # Visual Studio 2010 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CSharpProject", "http://localhost/CSharpProject/CSharpProject.csproj", "{686DD036-86AA-443E-8A10-DDB43266A8C4}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {686DD036-86AA-443E-8A10-DDB43266A8C4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {686DD036-86AA-443E-8A10-DDB43266A8C4}.Debug|Any CPU.Build.0 = Debug|Any CPU {686DD036-86AA-443E-8A10-DDB43266A8C4}.Release|Any CPU.ActiveCfg = Release|Any CPU {686DD036-86AA-443E-8A10-DDB43266A8C4}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal
 Microsoft Visual Studio Solution File, Format Version 11.00 # Visual Studio 2010 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CSharpProject", "http://localhost/CSharpProject/CSharpProject.csproj", "{686DD036-86AA-443E-8A10-DDB43266A8C4}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {686DD036-86AA-443E-8A10-DDB43266A8C4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {686DD036-86AA-443E-8A10-DDB43266A8C4}.Debug|Any CPU.Build.0 = Debug|Any CPU {686DD036-86AA-443E-8A10-DDB43266A8C4}.Release|Any CPU.ActiveCfg = Release|Any CPU {686DD036-86AA-443E-8A10-DDB43266A8C4}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/Compilers/VisualBasic/Test/Syntax/Syntax/SeparatedSyntaxListTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System Imports System.Collections.Generic Imports System.Linq Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class SeparatedSyntaxListTests <Fact> Public Sub TestAddInsertRemoveReplace() Dim list = SyntaxFactory.SeparatedList(Of SyntaxNode)(New SyntaxNode() { SyntaxFactory.ParseExpression("A"), SyntaxFactory.ParseExpression("B"), SyntaxFactory.ParseExpression("C")}) Assert.Equal(3, list.Count) Assert.Equal("A", list(0).ToString()) Assert.Equal("B", list(1).ToString()) Assert.Equal("C", list(2).ToString()) Assert.Equal("A,B,C", list.ToFullString()) Dim elementA = list(0) Dim elementB = list(1) Dim elementC = list(2) Assert.Equal(0, list.IndexOf(elementA)) Assert.Equal(1, list.IndexOf(elementB)) Assert.Equal(2, list.IndexOf(elementC)) Dim nodeD As SyntaxNode = SyntaxFactory.ParseExpression("D") Dim nodeE As SyntaxNode = SyntaxFactory.ParseExpression("E") Dim newList = list.Add(nodeD) Assert.Equal(4, newList.Count) Assert.Equal("A,B,C,D", newList.ToFullString()) newList = list.AddRange({nodeD, nodeE}) Assert.Equal(5, newList.Count) Assert.Equal("A,B,C,D,E", newList.ToFullString()) newList = list.Insert(0, nodeD) Assert.Equal(4, newList.Count) Assert.Equal("D,A,B,C", newList.ToFullString()) newList = list.Insert(1, nodeD) Assert.Equal(4, newList.Count) Assert.Equal("A,D,B,C", newList.ToFullString()) newList = list.Insert(2, nodeD) Assert.Equal(4, newList.Count) Assert.Equal("A,B,D,C", newList.ToFullString()) newList = list.Insert(3, nodeD) Assert.Equal(4, newList.Count) Assert.Equal("A,B,C,D", newList.ToFullString()) newList = list.InsertRange(0, {nodeD, nodeE}) Assert.Equal(5, newList.Count) Assert.Equal("D,E,A,B,C", newList.ToFullString()) newList = list.InsertRange(1, {nodeD, nodeE}) Assert.Equal(5, newList.Count) Assert.Equal("A,D,E,B,C", newList.ToFullString()) newList = list.InsertRange(2, {nodeD, nodeE}) Assert.Equal(5, newList.Count) Assert.Equal("A,B,D,E,C", newList.ToFullString()) newList = list.InsertRange(3, {nodeD, nodeE}) Assert.Equal(5, newList.Count) Assert.Equal("A,B,C,D,E", newList.ToFullString()) newList = list.RemoveAt(0) Assert.Equal(2, newList.Count) Assert.Equal("B,C", newList.ToFullString()) newList = list.RemoveAt(list.Count - 1) Assert.Equal(2, newList.Count) Assert.Equal("A,B", newList.ToFullString()) newList = list.Remove(elementA) Assert.Equal(2, newList.Count) Assert.Equal("B,C", newList.ToFullString()) newList = list.Remove(elementB) Assert.Equal(2, newList.Count) Assert.Equal("A,C", newList.ToFullString()) newList = list.Remove(elementC) Assert.Equal(2, newList.Count) Assert.Equal("A,B", newList.ToFullString()) newList = list.Replace(elementA, nodeD) Assert.Equal(3, newList.Count) Assert.Equal("D,B,C", newList.ToFullString()) newList = list.Replace(elementB, nodeD) Assert.Equal(3, newList.Count) Assert.Equal("A,D,C", newList.ToFullString()) newList = list.Replace(elementC, nodeD) Assert.Equal(3, newList.Count) Assert.Equal("A,B,D", newList.ToFullString()) newList = list.ReplaceRange(elementA, {nodeD, nodeE}) Assert.Equal(4, newList.Count) Assert.Equal("D,E,B,C", newList.ToFullString()) newList = list.ReplaceRange(elementB, {nodeD, nodeE}) Assert.Equal(4, newList.Count) Assert.Equal("A,D,E,C", newList.ToFullString()) newList = list.ReplaceRange(elementC, {nodeD, nodeE}) Assert.Equal(4, newList.Count) Assert.Equal("A,B,D,E", newList.ToFullString()) newList = list.ReplaceRange(elementA, New SyntaxNode() {}) Assert.Equal(2, newList.Count) Assert.Equal("B,C", newList.ToFullString()) newList = list.ReplaceRange(elementB, New SyntaxNode() {}) Assert.Equal(2, newList.Count) Assert.Equal("A,C", newList.ToFullString()) newList = list.ReplaceRange(elementC, New SyntaxNode() {}) Assert.Equal(2, newList.Count) Assert.Equal("A,B", newList.ToFullString()) Assert.Equal(-1, list.IndexOf(nodeD)) Assert.Throws(Of ArgumentOutOfRangeException)(Function() list.Insert(-1, nodeD)) Assert.Throws(Of ArgumentOutOfRangeException)(Function() list.Insert(list.Count + 1, nodeD)) Assert.Throws(Of ArgumentOutOfRangeException)(Function() list.InsertRange(-1, {nodeD})) Assert.Throws(Of ArgumentOutOfRangeException)(Function() list.InsertRange(list.Count + 1, {nodeD})) Assert.Throws(Of ArgumentOutOfRangeException)(Function() list.RemoveAt(-1)) Assert.Throws(Of ArgumentOutOfRangeException)(Function() list.RemoveAt(list.Count)) Assert.Throws(Of ArgumentOutOfRangeException)(Function() list.Replace(nodeD, nodeE)) Assert.Throws(Of ArgumentOutOfRangeException)(Function() list.ReplaceRange(nodeD, {nodeE})) Assert.Throws(Of ArgumentNullException)(Function() list.Add(Nothing)) Assert.Throws(Of ArgumentNullException)(Function() list.AddRange(DirectCast(Nothing, IEnumerable(Of SyntaxNode)))) Assert.Throws(Of ArgumentNullException)(Function() list.Insert(0, Nothing)) Assert.Throws(Of ArgumentNullException)(Function() list.InsertRange(0, DirectCast(Nothing, IEnumerable(Of SyntaxNode)))) Assert.Throws(Of ArgumentNullException)(Function() list.ReplaceRange(elementA, DirectCast(Nothing, IEnumerable(Of SyntaxNode)))) End Sub <Fact> Public Sub TestAddInsertRemoveReplaceOnEmptyList() DoTestAddInsertRemoveReplaceOnEmptyList(SyntaxFactory.SeparatedList(Of SyntaxNode)()) DoTestAddInsertRemoveReplaceOnEmptyList(Nothing) End Sub Private Sub DoTestAddInsertRemoveReplaceOnEmptyList(list As SeparatedSyntaxList(Of SyntaxNode)) Assert.Equal(0, list.Count) Dim nodeD As SyntaxNode = SyntaxFactory.ParseExpression("D") Dim nodeE As SyntaxNode = SyntaxFactory.ParseExpression("E") Dim newList = list.Add(nodeD) Assert.Equal(1, newList.Count) Assert.Equal("D", newList.ToFullString()) newList = list.AddRange({nodeD, nodeE}) Assert.Equal(2, newList.Count) Assert.Equal("D,E", newList.ToFullString()) newList = list.Insert(0, nodeD) Assert.Equal(1, newList.Count) Assert.Equal("D", newList.ToFullString()) newList = list.InsertRange(0, {nodeD, nodeE}) Assert.Equal(2, newList.Count) Assert.Equal("D,E", newList.ToFullString()) newList = list.Remove(nodeD) Assert.Equal(0, newList.Count) Assert.Equal(-1, list.IndexOf(nodeD)) Assert.Throws(Of ArgumentOutOfRangeException)(Function() list.RemoveAt(0)) Assert.Throws(Of ArgumentOutOfRangeException)(Function() list.Insert(1, nodeD)) Assert.Throws(Of ArgumentOutOfRangeException)(Function() list.Insert(-1, nodeD)) Assert.Throws(Of ArgumentOutOfRangeException)(Function() list.InsertRange(1, {nodeD})) Assert.Throws(Of ArgumentOutOfRangeException)(Function() list.InsertRange(-1, {nodeD})) Assert.Throws(Of ArgumentOutOfRangeException)(Function() list.Replace(nodeD, nodeE)) Assert.Throws(Of ArgumentOutOfRangeException)(Function() list.ReplaceRange(nodeD, {nodeE})) Assert.Throws(Of ArgumentNullException)(Function() list.Add(Nothing)) Assert.Throws(Of ArgumentNullException)(Function() list.AddRange(DirectCast(Nothing, IEnumerable(Of SyntaxNode)))) Assert.Throws(Of ArgumentNullException)(Function() list.Insert(0, Nothing)) Assert.Throws(Of ArgumentNullException)(Function() list.InsertRange(0, DirectCast(Nothing, IEnumerable(Of SyntaxNode)))) End Sub <Fact> Public Sub Extensions() Dim list = SyntaxFactory.SeparatedList(New SyntaxNode() { SyntaxFactory.ParseExpression("A+B"), SyntaxFactory.IdentifierName("B"), SyntaxFactory.ParseExpression("1")}) Assert.Equal(0, list.IndexOf(SyntaxKind.AddExpression)) Assert.True(list.Any(SyntaxKind.AddExpression)) Assert.Equal(1, list.IndexOf(SyntaxKind.IdentifierName)) Assert.True(list.Any(SyntaxKind.IdentifierName)) Assert.Equal(2, list.IndexOf(SyntaxKind.NumericLiteralExpression)) Assert.True(list.Any(SyntaxKind.NumericLiteralExpression)) Assert.Equal(-1, list.IndexOf(SyntaxKind.WhereClause)) Assert.False(list.Any(SyntaxKind.WhereClause)) 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 Imports System.Collections.Generic Imports System.Linq Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class SeparatedSyntaxListTests <Fact> Public Sub TestAddInsertRemoveReplace() Dim list = SyntaxFactory.SeparatedList(Of SyntaxNode)(New SyntaxNode() { SyntaxFactory.ParseExpression("A"), SyntaxFactory.ParseExpression("B"), SyntaxFactory.ParseExpression("C")}) Assert.Equal(3, list.Count) Assert.Equal("A", list(0).ToString()) Assert.Equal("B", list(1).ToString()) Assert.Equal("C", list(2).ToString()) Assert.Equal("A,B,C", list.ToFullString()) Dim elementA = list(0) Dim elementB = list(1) Dim elementC = list(2) Assert.Equal(0, list.IndexOf(elementA)) Assert.Equal(1, list.IndexOf(elementB)) Assert.Equal(2, list.IndexOf(elementC)) Dim nodeD As SyntaxNode = SyntaxFactory.ParseExpression("D") Dim nodeE As SyntaxNode = SyntaxFactory.ParseExpression("E") Dim newList = list.Add(nodeD) Assert.Equal(4, newList.Count) Assert.Equal("A,B,C,D", newList.ToFullString()) newList = list.AddRange({nodeD, nodeE}) Assert.Equal(5, newList.Count) Assert.Equal("A,B,C,D,E", newList.ToFullString()) newList = list.Insert(0, nodeD) Assert.Equal(4, newList.Count) Assert.Equal("D,A,B,C", newList.ToFullString()) newList = list.Insert(1, nodeD) Assert.Equal(4, newList.Count) Assert.Equal("A,D,B,C", newList.ToFullString()) newList = list.Insert(2, nodeD) Assert.Equal(4, newList.Count) Assert.Equal("A,B,D,C", newList.ToFullString()) newList = list.Insert(3, nodeD) Assert.Equal(4, newList.Count) Assert.Equal("A,B,C,D", newList.ToFullString()) newList = list.InsertRange(0, {nodeD, nodeE}) Assert.Equal(5, newList.Count) Assert.Equal("D,E,A,B,C", newList.ToFullString()) newList = list.InsertRange(1, {nodeD, nodeE}) Assert.Equal(5, newList.Count) Assert.Equal("A,D,E,B,C", newList.ToFullString()) newList = list.InsertRange(2, {nodeD, nodeE}) Assert.Equal(5, newList.Count) Assert.Equal("A,B,D,E,C", newList.ToFullString()) newList = list.InsertRange(3, {nodeD, nodeE}) Assert.Equal(5, newList.Count) Assert.Equal("A,B,C,D,E", newList.ToFullString()) newList = list.RemoveAt(0) Assert.Equal(2, newList.Count) Assert.Equal("B,C", newList.ToFullString()) newList = list.RemoveAt(list.Count - 1) Assert.Equal(2, newList.Count) Assert.Equal("A,B", newList.ToFullString()) newList = list.Remove(elementA) Assert.Equal(2, newList.Count) Assert.Equal("B,C", newList.ToFullString()) newList = list.Remove(elementB) Assert.Equal(2, newList.Count) Assert.Equal("A,C", newList.ToFullString()) newList = list.Remove(elementC) Assert.Equal(2, newList.Count) Assert.Equal("A,B", newList.ToFullString()) newList = list.Replace(elementA, nodeD) Assert.Equal(3, newList.Count) Assert.Equal("D,B,C", newList.ToFullString()) newList = list.Replace(elementB, nodeD) Assert.Equal(3, newList.Count) Assert.Equal("A,D,C", newList.ToFullString()) newList = list.Replace(elementC, nodeD) Assert.Equal(3, newList.Count) Assert.Equal("A,B,D", newList.ToFullString()) newList = list.ReplaceRange(elementA, {nodeD, nodeE}) Assert.Equal(4, newList.Count) Assert.Equal("D,E,B,C", newList.ToFullString()) newList = list.ReplaceRange(elementB, {nodeD, nodeE}) Assert.Equal(4, newList.Count) Assert.Equal("A,D,E,C", newList.ToFullString()) newList = list.ReplaceRange(elementC, {nodeD, nodeE}) Assert.Equal(4, newList.Count) Assert.Equal("A,B,D,E", newList.ToFullString()) newList = list.ReplaceRange(elementA, New SyntaxNode() {}) Assert.Equal(2, newList.Count) Assert.Equal("B,C", newList.ToFullString()) newList = list.ReplaceRange(elementB, New SyntaxNode() {}) Assert.Equal(2, newList.Count) Assert.Equal("A,C", newList.ToFullString()) newList = list.ReplaceRange(elementC, New SyntaxNode() {}) Assert.Equal(2, newList.Count) Assert.Equal("A,B", newList.ToFullString()) Assert.Equal(-1, list.IndexOf(nodeD)) Assert.Throws(Of ArgumentOutOfRangeException)(Function() list.Insert(-1, nodeD)) Assert.Throws(Of ArgumentOutOfRangeException)(Function() list.Insert(list.Count + 1, nodeD)) Assert.Throws(Of ArgumentOutOfRangeException)(Function() list.InsertRange(-1, {nodeD})) Assert.Throws(Of ArgumentOutOfRangeException)(Function() list.InsertRange(list.Count + 1, {nodeD})) Assert.Throws(Of ArgumentOutOfRangeException)(Function() list.RemoveAt(-1)) Assert.Throws(Of ArgumentOutOfRangeException)(Function() list.RemoveAt(list.Count)) Assert.Throws(Of ArgumentOutOfRangeException)(Function() list.Replace(nodeD, nodeE)) Assert.Throws(Of ArgumentOutOfRangeException)(Function() list.ReplaceRange(nodeD, {nodeE})) Assert.Throws(Of ArgumentNullException)(Function() list.Add(Nothing)) Assert.Throws(Of ArgumentNullException)(Function() list.AddRange(DirectCast(Nothing, IEnumerable(Of SyntaxNode)))) Assert.Throws(Of ArgumentNullException)(Function() list.Insert(0, Nothing)) Assert.Throws(Of ArgumentNullException)(Function() list.InsertRange(0, DirectCast(Nothing, IEnumerable(Of SyntaxNode)))) Assert.Throws(Of ArgumentNullException)(Function() list.ReplaceRange(elementA, DirectCast(Nothing, IEnumerable(Of SyntaxNode)))) End Sub <Fact> Public Sub TestAddInsertRemoveReplaceOnEmptyList() DoTestAddInsertRemoveReplaceOnEmptyList(SyntaxFactory.SeparatedList(Of SyntaxNode)()) DoTestAddInsertRemoveReplaceOnEmptyList(Nothing) End Sub Private Sub DoTestAddInsertRemoveReplaceOnEmptyList(list As SeparatedSyntaxList(Of SyntaxNode)) Assert.Equal(0, list.Count) Dim nodeD As SyntaxNode = SyntaxFactory.ParseExpression("D") Dim nodeE As SyntaxNode = SyntaxFactory.ParseExpression("E") Dim newList = list.Add(nodeD) Assert.Equal(1, newList.Count) Assert.Equal("D", newList.ToFullString()) newList = list.AddRange({nodeD, nodeE}) Assert.Equal(2, newList.Count) Assert.Equal("D,E", newList.ToFullString()) newList = list.Insert(0, nodeD) Assert.Equal(1, newList.Count) Assert.Equal("D", newList.ToFullString()) newList = list.InsertRange(0, {nodeD, nodeE}) Assert.Equal(2, newList.Count) Assert.Equal("D,E", newList.ToFullString()) newList = list.Remove(nodeD) Assert.Equal(0, newList.Count) Assert.Equal(-1, list.IndexOf(nodeD)) Assert.Throws(Of ArgumentOutOfRangeException)(Function() list.RemoveAt(0)) Assert.Throws(Of ArgumentOutOfRangeException)(Function() list.Insert(1, nodeD)) Assert.Throws(Of ArgumentOutOfRangeException)(Function() list.Insert(-1, nodeD)) Assert.Throws(Of ArgumentOutOfRangeException)(Function() list.InsertRange(1, {nodeD})) Assert.Throws(Of ArgumentOutOfRangeException)(Function() list.InsertRange(-1, {nodeD})) Assert.Throws(Of ArgumentOutOfRangeException)(Function() list.Replace(nodeD, nodeE)) Assert.Throws(Of ArgumentOutOfRangeException)(Function() list.ReplaceRange(nodeD, {nodeE})) Assert.Throws(Of ArgumentNullException)(Function() list.Add(Nothing)) Assert.Throws(Of ArgumentNullException)(Function() list.AddRange(DirectCast(Nothing, IEnumerable(Of SyntaxNode)))) Assert.Throws(Of ArgumentNullException)(Function() list.Insert(0, Nothing)) Assert.Throws(Of ArgumentNullException)(Function() list.InsertRange(0, DirectCast(Nothing, IEnumerable(Of SyntaxNode)))) End Sub <Fact> Public Sub Extensions() Dim list = SyntaxFactory.SeparatedList(New SyntaxNode() { SyntaxFactory.ParseExpression("A+B"), SyntaxFactory.IdentifierName("B"), SyntaxFactory.ParseExpression("1")}) Assert.Equal(0, list.IndexOf(SyntaxKind.AddExpression)) Assert.True(list.Any(SyntaxKind.AddExpression)) Assert.Equal(1, list.IndexOf(SyntaxKind.IdentifierName)) Assert.True(list.Any(SyntaxKind.IdentifierName)) Assert.Equal(2, list.IndexOf(SyntaxKind.NumericLiteralExpression)) Assert.True(list.Any(SyntaxKind.NumericLiteralExpression)) Assert.Equal(-1, list.IndexOf(SyntaxKind.WhereClause)) Assert.False(list.Any(SyntaxKind.WhereClause)) End Sub End Class End Namespace
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/Workspaces/Core/Portable/Options/IOptionPersister.cs
// Licensed to the .NET Foundation under one or more 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> /// Exportable by a host to specify the save and restore behavior for a particular set of /// values. /// </summary> internal interface IOptionPersister { bool TryFetch(OptionKey optionKey, out object? value); bool TryPersist(OptionKey optionKey, object? value); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.Options { /// <summary> /// Exportable by a host to specify the save and restore behavior for a particular set of /// values. /// </summary> internal interface IOptionPersister { bool TryFetch(OptionKey optionKey, out object? value); bool TryPersist(OptionKey optionKey, object? value); } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/Features/Core/Portable/UnifiedSuggestions/UnifiedSuggestedActionSetComparer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.UnifiedSuggestions { internal class UnifiedSuggestedActionSetComparer : IComparer<UnifiedSuggestedActionSet> { private readonly TextSpan? _targetSpan; public UnifiedSuggestedActionSetComparer(TextSpan? targetSpan) => _targetSpan = targetSpan; private static int Distance(TextSpan? maybeA, TextSpan? maybeB) { // If we don't have a text span or target point we cannot calculate the distance between them if (!maybeA.HasValue || !maybeB.HasValue) { return int.MaxValue; } var a = maybeA.Value; var b = maybeB.Value; // The distance of two spans is symetric sumation of: // - the distance of a's start to b's start // - the distance of a's end to b's end // // This particular metric has been chosen because it is both simple // and uses the all the information in both spans. A weighting (i.e. // the distance of starts is more important) could be added but it // didn't seem necessary. // // E.g.: for spans [ ] and $ $ the distance is distanceOfStarts+distanceOfEnds: // $ $ [ ] has distance 2+3 // $ [ ]$ has distance 1+0 // $[ ]$ has distance 0+0 // $ [] $ has distance 1+3 // $[] $ has distance 0+4 var startsDistance = Math.Abs(a.Start - b.Start); var endsDistance = Math.Abs(a.End - b.End); return startsDistance + endsDistance; } public int Compare(UnifiedSuggestedActionSet x, UnifiedSuggestedActionSet y) { if (!_targetSpan.HasValue || !x.ApplicableToSpan.HasValue || !y.ApplicableToSpan.HasValue) { // Not enough data to compare, consider them equal return 0; } var distanceX = Distance(x.ApplicableToSpan, _targetSpan); var distanceY = Distance(y.ApplicableToSpan, _targetSpan); return distanceX.CompareTo(distanceY); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.UnifiedSuggestions { internal class UnifiedSuggestedActionSetComparer : IComparer<UnifiedSuggestedActionSet> { private readonly TextSpan? _targetSpan; public UnifiedSuggestedActionSetComparer(TextSpan? targetSpan) => _targetSpan = targetSpan; private static int Distance(TextSpan? maybeA, TextSpan? maybeB) { // If we don't have a text span or target point we cannot calculate the distance between them if (!maybeA.HasValue || !maybeB.HasValue) { return int.MaxValue; } var a = maybeA.Value; var b = maybeB.Value; // The distance of two spans is symetric sumation of: // - the distance of a's start to b's start // - the distance of a's end to b's end // // This particular metric has been chosen because it is both simple // and uses the all the information in both spans. A weighting (i.e. // the distance of starts is more important) could be added but it // didn't seem necessary. // // E.g.: for spans [ ] and $ $ the distance is distanceOfStarts+distanceOfEnds: // $ $ [ ] has distance 2+3 // $ [ ]$ has distance 1+0 // $[ ]$ has distance 0+0 // $ [] $ has distance 1+3 // $[] $ has distance 0+4 var startsDistance = Math.Abs(a.Start - b.Start); var endsDistance = Math.Abs(a.End - b.End); return startsDistance + endsDistance; } public int Compare(UnifiedSuggestedActionSet x, UnifiedSuggestedActionSet y) { if (!_targetSpan.HasValue || !x.ApplicableToSpan.HasValue || !y.ApplicableToSpan.HasValue) { // Not enough data to compare, consider them equal return 0; } var distanceX = Distance(x.ApplicableToSpan, _targetSpan); var distanceY = Distance(y.ApplicableToSpan, _targetSpan); return distanceX.CompareTo(distanceY); } } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/Compilers/VisualBasic/Test/Emit/PDB/PDBTests.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.IO Imports System.Reflection.Metadata Imports System.Reflection.Metadata.Ecma335 Imports System.Reflection.PortableExecutable Imports System.Text Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.PDB Public Class PDBTests Inherits BasicTestBase #Region "General" <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub EmitDebugInfoForSourceTextWithoutEncoding1() Dim tree1 = SyntaxFactory.ParseSyntaxTree("Class A : End Class", path:="Goo.vb", encoding:=Nothing) Dim tree2 = SyntaxFactory.ParseSyntaxTree("Class B : End Class", path:="", encoding:=Nothing) Dim tree3 = SyntaxFactory.ParseSyntaxTree(SourceText.From("Class C : End Class", encoding:=Nothing), path:="Bar.vb") Dim tree4 = SyntaxFactory.ParseSyntaxTree("Class D : End Class", path:="Baz.vb", encoding:=Encoding.UTF8) Dim comp = VisualBasicCompilation.Create("Compilation", {tree1, tree2, tree3, tree4}, {MscorlibRef}, options:=TestOptions.ReleaseDll) Dim result = comp.Emit(New MemoryStream(), pdbStream:=New MemoryStream()) result.Diagnostics.Verify( Diagnostic(ERRID.ERR_EncodinglessSyntaxTree, "Class A : End Class").WithLocation(1, 1), Diagnostic(ERRID.ERR_EncodinglessSyntaxTree, "Class C : End Class").WithLocation(1, 1)) Assert.False(result.Success) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub EmitDebugInfoForSourceTextWithoutEncoding2() Dim tree1 = SyntaxFactory.ParseSyntaxTree("Class A" & vbCrLf & "Sub F() : End Sub : End Class", path:="Goo.vb", encoding:=Encoding.Unicode) Dim tree2 = SyntaxFactory.ParseSyntaxTree("Class B" & vbCrLf & "Sub F() : End Sub : End Class", path:="", encoding:=Nothing) Dim tree3 = SyntaxFactory.ParseSyntaxTree("Class C" & vbCrLf & "Sub F() : End Sub : End Class", path:="Bar.vb", encoding:=New UTF8Encoding(True, False)) Dim tree4 = SyntaxFactory.ParseSyntaxTree(SourceText.From("Class D" & vbCrLf & "Sub F() : End Sub : End Class", New UTF8Encoding(False, False)), path:="Baz.vb") Dim comp = VisualBasicCompilation.Create("Compilation", {tree1, tree2, tree3, tree4}, {MscorlibRef}, options:=TestOptions.ReleaseDll) Dim result = comp.Emit(New MemoryStream(), pdbStream:=New MemoryStream()) result.Diagnostics.Verify() Assert.True(result.Success) Dim hash1 = CryptographicHashProvider.ComputeSha1(Encoding.Unicode.GetBytesWithPreamble(tree1.ToString())).ToArray() Dim hash3 = CryptographicHashProvider.ComputeSha1(New UTF8Encoding(True, False).GetBytesWithPreamble(tree3.ToString())).ToArray() Dim hash4 = CryptographicHashProvider.ComputeSha1(New UTF8Encoding(False, False).GetBytesWithPreamble(tree4.ToString())).ToArray() comp.VerifyPdb( <symbols> <files> <file id="1" name="Goo.vb" language="VB" checksumAlgorithm="SHA1" checksum=<%= BitConverter.ToString(hash1) %>/> <file id="2" name="" language="VB"/> <file id="3" name="Bar.vb" language="VB" checksumAlgorithm="SHA1" checksum=<%= BitConverter.ToString(hash3) %>/> <file id="4" name="Baz.vb" language="VB" checksumAlgorithm="SHA1" checksum=<%= BitConverter.ToString(hash4) %>/> </files> </symbols>, options:=PdbValidationOptions.ExcludeMethods) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub CustomDebugEntryPoint_DLL() Dim source = " Class C Shared Sub F() End Sub End Class " Dim c = CreateCompilationWithMscorlib40({source}, options:=TestOptions.DebugDll) Dim f = c.GetMember(Of MethodSymbol)("C.F") c.VerifyPdb( <symbols> <files> <file id="1" name="" language="VB"/> </files> <entryPoint declaringType="C" methodName="F"/> <methods/> </symbols>, debugEntryPoint:=f, options:=PdbValidationOptions.ExcludeScopes Or PdbValidationOptions.ExcludeSequencePoints Or PdbValidationOptions.ExcludeCustomDebugInformation) Dim peReader = New PEReader(c.EmitToArray(debugEntryPoint:=f)) Dim peEntryPointToken = peReader.PEHeaders.CorHeader.EntryPointTokenOrRelativeVirtualAddress Assert.Equal(0, peEntryPointToken) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub CustomDebugEntryPoint_EXE() Dim source = " Class M Shared Sub Main() End Sub End Class Class C Shared Sub F(Of S)() End Sub End Class " Dim c = CreateCompilationWithMscorlib40({source}, options:=TestOptions.DebugExe) Dim f = c.GetMember(Of MethodSymbol)("C.F") c.VerifyPdb( <symbols> <files> <file id="1" name="" language="VB"/> </files> <entryPoint declaringType="C" methodName="F"/> <methods/> </symbols>, debugEntryPoint:=f, options:=PdbValidationOptions.ExcludeScopes Or PdbValidationOptions.ExcludeSequencePoints Or PdbValidationOptions.ExcludeCustomDebugInformation) Dim peReader = New PEReader(c.EmitToArray(debugEntryPoint:=f)) Dim peEntryPointToken = peReader.PEHeaders.CorHeader.EntryPointTokenOrRelativeVirtualAddress Dim mdReader = peReader.GetMetadataReader() Dim methodDef = mdReader.GetMethodDefinition(CType(MetadataTokens.Handle(peEntryPointToken), MethodDefinitionHandle)) Assert.Equal("Main", mdReader.GetString(methodDef.Name)) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub CustomDebugEntryPoint_Errors() Dim source1 = " Class C Shared Sub F End Sub End Class Class D(Of T) Shared Sub G(Of S)() End Sub End Class " Dim source2 = " Class C Shared Sub F() End Sub End Class " Dim c1 = CreateCompilationWithMscorlib40({source1}, options:=TestOptions.DebugDll) Dim c2 = CreateCompilationWithMscorlib40({source2}, options:=TestOptions.DebugDll) Dim f1 = c1.GetMember(Of MethodSymbol)("C.F") Dim f2 = c2.GetMember(Of MethodSymbol)("C.F") Dim g = c1.GetMember(Of MethodSymbol)("D.G") Dim d = c1.GetMember(Of NamedTypeSymbol)("D") Assert.NotNull(f1) Assert.NotNull(f2) Assert.NotNull(g) Assert.NotNull(d) Dim stInt = c1.GetSpecialType(SpecialType.System_Int32) Dim d_t_g_int = g.Construct(stInt) Dim d_int = d.Construct(stInt) Dim d_int_g = d_int.GetMember(Of MethodSymbol)("G") Dim d_int_g_int = d_int_g.Construct(stInt) Dim result = c1.Emit(New MemoryStream(), New MemoryStream(), debugEntryPoint:=f2) result.Diagnostics.Verify(Diagnostic(ERRID.ERR_DebugEntryPointNotSourceMethodDefinition)) result = c1.Emit(New MemoryStream(), New MemoryStream(), debugEntryPoint:=d_t_g_int) result.Diagnostics.Verify(Diagnostic(ERRID.ERR_DebugEntryPointNotSourceMethodDefinition)) result = c1.Emit(New MemoryStream(), New MemoryStream(), debugEntryPoint:=d_int_g) result.Diagnostics.Verify(Diagnostic(ERRID.ERR_DebugEntryPointNotSourceMethodDefinition)) result = c1.Emit(New MemoryStream(), New MemoryStream(), debugEntryPoint:=d_int_g_int) result.Diagnostics.Verify(Diagnostic(ERRID.ERR_DebugEntryPointNotSourceMethodDefinition)) End Sub #End Region <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub TestBasic() Dim source = <compilation> <file><![CDATA[ Class C1 Sub Method() System.Console.WriteLine("Hello, world.") End Sub End Class ]]></file> </compilation> Dim defines = PredefinedPreprocessorSymbols.AddPredefinedPreprocessorSymbols(OutputKind.ConsoleApplication) defines = defines.Add(KeyValuePairUtil.Create("_MyType", CObj("Console"))) Dim parseOptions = New VisualBasicParseOptions(preprocessorSymbols:=defines) Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugDll.WithParseOptions(parseOptions)) compilation.VerifyPdb( <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="My.MyComputer" name=".ctor"> <sequencePoints> <entry offset="0x0" startLine="109" startColumn="9" endLine="109" endColumn="25" document="1"/> <entry offset="0x1" startLine="110" startColumn="13" endLine="110" endColumn="25" document="1"/> <entry offset="0x8" startLine="111" startColumn="9" endLine="111" endColumn="16" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x9"> <currentnamespace name="My"/> </scope> </method> <method containingType="My.MyProject" name=".cctor"> <sequencePoints> <entry offset="0x0" startLine="128" startColumn="26" endLine="128" endColumn="97" document="1"/> <entry offset="0xa" startLine="139" startColumn="26" endLine="139" endColumn="95" document="1"/> <entry offset="0x14" startLine="150" startColumn="26" endLine="150" endColumn="136" document="1"/> <entry offset="0x1e" startLine="286" startColumn="26" endLine="286" endColumn="105" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x29"> <importsforward declaringType="My.MyComputer" methodName=".ctor"/> </scope> </method> <method containingType="My.MyProject" name="get_Computer"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="123" startColumn="13" endLine="123" endColumn="16" document="1"/> <entry offset="0x1" startLine="124" startColumn="17" endLine="124" endColumn="62" document="1"/> <entry offset="0xe" startLine="125" startColumn="13" endLine="125" endColumn="20" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x10"> <importsforward declaringType="My.MyComputer" methodName=".ctor"/> <local name="Computer" il_index="0" il_start="0x0" il_end="0x10" attributes="0"/> </scope> </method> <method containingType="My.MyProject" name="get_Application"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="135" startColumn="13" endLine="135" endColumn="16" document="1"/> <entry offset="0x1" startLine="136" startColumn="17" endLine="136" endColumn="57" document="1"/> <entry offset="0xe" startLine="137" startColumn="13" endLine="137" endColumn="20" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x10"> <importsforward declaringType="My.MyComputer" methodName=".ctor"/> <local name="Application" il_index="0" il_start="0x0" il_end="0x10" attributes="0"/> </scope> </method> <method containingType="My.MyProject" name="get_User"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="146" startColumn="13" endLine="146" endColumn="16" document="1"/> <entry offset="0x1" startLine="147" startColumn="17" endLine="147" endColumn="58" document="1"/> <entry offset="0xe" startLine="148" startColumn="13" endLine="148" endColumn="20" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x10"> <importsforward declaringType="My.MyComputer" methodName=".ctor"/> <local name="User" il_index="0" il_start="0x0" il_end="0x10" attributes="0"/> </scope> </method> <method containingType="My.MyProject" name="get_WebServices"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="239" startColumn="14" endLine="239" endColumn="17" document="1"/> <entry offset="0x1" startLine="240" startColumn="17" endLine="240" endColumn="67" document="1"/> <entry offset="0xe" startLine="241" startColumn="13" endLine="241" endColumn="20" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x10"> <importsforward declaringType="My.MyComputer" methodName=".ctor"/> <local name="WebServices" il_index="0" il_start="0x0" il_end="0x10" attributes="0"/> </scope> </method> <method containingType="C1" name="Method"> <sequencePoints> <entry offset="0x0" startLine="2" startColumn="5" endLine="2" endColumn="17" document="1"/> <entry offset="0x1" startLine="3" startColumn="9" endLine="3" endColumn="50" document="1"/> <entry offset="0xc" startLine="4" startColumn="5" endLine="4" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0xd"> <currentnamespace name=""/> </scope> </method> <method containingType="My.MyProject+MyWebServices" name="Equals" parameterNames="o"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="249" startColumn="13" endLine="249" endColumn="75" document="1"/> <entry offset="0x1" startLine="250" startColumn="17" endLine="250" endColumn="40" document="1"/> <entry offset="0x10" startLine="251" startColumn="13" endLine="251" endColumn="25" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x12"> <currentnamespace name="My"/> <local name="Equals" il_index="0" il_start="0x0" il_end="0x12" attributes="0"/> </scope> </method> <method containingType="My.MyProject+MyWebServices" name="GetHashCode"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="253" startColumn="13" endLine="253" endColumn="63" document="1"/> <entry offset="0x1" startLine="254" startColumn="17" endLine="254" endColumn="42" document="1"/> <entry offset="0xa" startLine="255" startColumn="13" endLine="255" endColumn="25" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0xc"> <importsforward declaringType="My.MyProject+MyWebServices" methodName="Equals" parameterNames="o"/> <local name="GetHashCode" il_index="0" il_start="0x0" il_end="0xc" attributes="0"/> </scope> </method> <method containingType="My.MyProject+MyWebServices" name="GetType"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="257" startColumn="13" endLine="257" endColumn="72" document="1"/> <entry offset="0x1" startLine="258" startColumn="17" endLine="258" endColumn="46" document="1"/> <entry offset="0xe" startLine="259" startColumn="13" endLine="259" endColumn="25" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x10"> <importsforward declaringType="My.MyProject+MyWebServices" methodName="Equals" parameterNames="o"/> <local name="GetType" il_index="0" il_start="0x0" il_end="0x10" attributes="0"/> </scope> </method> <method containingType="My.MyProject+MyWebServices" name="ToString"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="261" startColumn="13" endLine="261" endColumn="59" document="1"/> <entry offset="0x1" startLine="262" startColumn="17" endLine="262" endColumn="39" document="1"/> <entry offset="0xa" startLine="263" startColumn="13" endLine="263" endColumn="25" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0xc"> <importsforward declaringType="My.MyProject+MyWebServices" methodName="Equals" parameterNames="o"/> <local name="ToString" il_index="0" il_start="0x0" il_end="0xc" attributes="0"/> </scope> </method> <method containingType="My.MyProject+MyWebServices" name="Create__Instance__" parameterNames="instance"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> <slot kind="1" offset="0"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="266" startColumn="12" endLine="266" endColumn="95" document="1"/> <entry offset="0x1" startLine="267" startColumn="17" endLine="267" endColumn="44" document="1"/> <entry offset="0xb" hidden="true" document="1"/> <entry offset="0xe" startLine="268" startColumn="21" endLine="268" endColumn="35" document="1"/> <entry offset="0x16" startLine="269" startColumn="17" endLine="269" endColumn="21" document="1"/> <entry offset="0x17" startLine="270" startColumn="21" endLine="270" endColumn="36" document="1"/> <entry offset="0x1b" startLine="272" startColumn="13" endLine="272" endColumn="25" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x1d"> <importsforward declaringType="My.MyProject+MyWebServices" methodName="Equals" parameterNames="o"/> <local name="Create__Instance__" il_index="0" il_start="0x0" il_end="0x1d" attributes="0"/> </scope> </method> <method containingType="My.MyProject+MyWebServices" name="Dispose__Instance__" parameterNames="instance"> <sequencePoints> <entry offset="0x0" startLine="275" startColumn="13" endLine="275" endColumn="71" document="1"/> <entry offset="0x1" startLine="276" startColumn="17" endLine="276" endColumn="35" document="1"/> <entry offset="0x8" startLine="277" startColumn="13" endLine="277" endColumn="20" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x9"> <importsforward declaringType="My.MyProject+MyWebServices" methodName="Equals" parameterNames="o"/> </scope> </method> <method containingType="My.MyProject+MyWebServices" name=".ctor"> <sequencePoints> <entry offset="0x0" startLine="281" startColumn="13" endLine="281" endColumn="29" document="1"/> <entry offset="0x1" startLine="282" startColumn="16" endLine="282" endColumn="28" document="1"/> <entry offset="0x8" startLine="283" startColumn="13" endLine="283" endColumn="20" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x9"> <importsforward declaringType="My.MyProject+MyWebServices" methodName="Equals" parameterNames="o"/> </scope> </method> <method containingType="My.MyProject+ThreadSafeObjectProvider`1" name="get_GetInstance"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> <slot kind="1" offset="0"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="343" startColumn="17" endLine="343" endColumn="20" document="1"/> <entry offset="0x1" startLine="344" startColumn="21" endLine="344" endColumn="59" document="1"/> <entry offset="0xf" hidden="true" document="1"/> <entry offset="0x12" startLine="344" startColumn="60" endLine="344" endColumn="87" document="1"/> <entry offset="0x1c" startLine="345" startColumn="21" endLine="345" endColumn="47" document="1"/> <entry offset="0x24" startLine="346" startColumn="17" endLine="346" endColumn="24" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x26"> <importsforward declaringType="My.MyProject+MyWebServices" methodName="Equals" parameterNames="o"/> <local name="GetInstance" il_index="0" il_start="0x0" il_end="0x26" attributes="0"/> </scope> </method> <method containingType="My.MyProject+ThreadSafeObjectProvider`1" name=".ctor"> <sequencePoints> <entry offset="0x0" startLine="352" startColumn="13" endLine="352" endColumn="29" document="1"/> <entry offset="0x1" startLine="353" startColumn="17" endLine="353" endColumn="29" document="1"/> <entry offset="0x8" startLine="354" startColumn="13" endLine="354" endColumn="20" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x9"> <importsforward declaringType="My.MyProject+MyWebServices" methodName="Equals" parameterNames="o"/> </scope> </method> </methods> </symbols>, options:=PdbValidationOptions.SkipConversionValidation) ' TODO: https://github.com/dotnet/roslyn/issues/18004 End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub ConstructorsWithoutInitializers() Dim source = <compilation> <file><![CDATA[ Class C Sub New() Dim o As Object End Sub Sub New(x As Object) Dim y As Object = x End Sub End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) compilation.VerifyPdb("C..ctor", <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="C" name=".ctor"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="2" startColumn="5" endLine="2" endColumn="14" document="1"/> <entry offset="0x8" startLine="4" startColumn="5" endLine="4" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x9"> <currentnamespace name=""/> <local name="o" il_index="0" il_start="0x0" il_end="0x9" attributes="0"/> </scope> </method> <method containingType="C" name=".ctor" parameterNames="x"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="5" startColumn="5" endLine="5" endColumn="25" document="1"/> <entry offset="0x8" startLine="6" startColumn="13" endLine="6" endColumn="28" document="1"/> <entry offset="0xf" startLine="7" startColumn="5" endLine="7" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x10"> <importsforward declaringType="C" methodName=".ctor"/> <local name="y" il_index="0" il_start="0x0" il_end="0x10" attributes="0"/> </scope> </method> </methods> </symbols>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub ConstructorsWithInitializers() Dim source = <compilation> <file><![CDATA[ Class C Shared G As Object = 1 Private F As Object = G Sub New() Dim o As Object End Sub Sub New(x As Object) Dim y As Object = x End Sub End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) compilation.VerifyPdb("C..ctor", <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="C" name=".ctor"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="4" startColumn="5" endLine="4" endColumn="14" document="1"/> <entry offset="0x8" startLine="3" startColumn="13" endLine="3" endColumn="28" document="1"/> <entry offset="0x18" startLine="6" startColumn="5" endLine="6" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x19"> <importsforward declaringType="C" methodName=".cctor"/> <local name="o" il_index="0" il_start="0x0" il_end="0x19" attributes="0"/> </scope> </method> <method containingType="C" name=".ctor" parameterNames="x"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="7" startColumn="5" endLine="7" endColumn="25" document="1"/> <entry offset="0x8" startLine="3" startColumn="13" endLine="3" endColumn="28" document="1"/> <entry offset="0x18" startLine="8" startColumn="13" endLine="8" endColumn="28" document="1"/> <entry offset="0x1f" startLine="9" startColumn="5" endLine="9" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x20"> <importsforward declaringType="C" methodName=".cctor"/> <local name="y" il_index="0" il_start="0x0" il_end="0x20" attributes="0"/> </scope> </method> </methods> </symbols>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub TryCatchFinally() Dim source = <compilation> <file><![CDATA[ Option Strict On Imports System Module M1 Public Sub Main() Dim x As Integer = 0 Try Dim y As String = "y" label1: label2: If x = 0 Then Throw New Exception() End If Catch ex As Exception Dim z As String = "z" Console.WriteLine(x) x = 1 GoTo label1 Finally Dim q As String = "q" Console.WriteLine(x) End Try Console.WriteLine(x) End Sub End Module ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe) compilation.VerifyPdb("M1.Main", <symbols> <files> <file id="1" name="" language="VB"/> </files> <entryPoint declaringType="M1" methodName="Main"/> <methods> <method containingType="M1" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> <slot kind="0" offset="51"/> <slot kind="1" offset="100"/> <slot kind="0" offset="182"/> <slot kind="0" offset="221"/> <slot kind="0" offset="351"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="5" startColumn="5" endLine="5" endColumn="22" document="1"/> <entry offset="0x1" startLine="6" startColumn="13" endLine="6" endColumn="29" document="1"/> <entry offset="0x3" startLine="7" startColumn="9" endLine="7" endColumn="12" document="1"/> <entry offset="0x4" startLine="8" startColumn="17" endLine="8" endColumn="34" document="1"/> <entry offset="0xa" startLine="9" startColumn="1" endLine="9" endColumn="8" document="1"/> <entry offset="0xb" startLine="10" startColumn="1" endLine="10" endColumn="8" document="1"/> <entry offset="0xc" startLine="11" startColumn="13" endLine="11" endColumn="26" document="1"/> <entry offset="0x11" hidden="true" document="1"/> <entry offset="0x14" startLine="12" startColumn="17" endLine="12" endColumn="38" document="1"/> <entry offset="0x1a" startLine="13" startColumn="13" endLine="13" endColumn="19" document="1"/> <entry offset="0x1d" hidden="true" document="1"/> <entry offset="0x24" startLine="14" startColumn="9" endLine="14" endColumn="30" document="1"/> <entry offset="0x25" startLine="15" startColumn="17" endLine="15" endColumn="34" document="1"/> <entry offset="0x2c" startLine="16" startColumn="13" endLine="16" endColumn="33" document="1"/> <entry offset="0x33" startLine="17" startColumn="13" endLine="17" endColumn="18" document="1"/> <entry offset="0x35" startLine="18" startColumn="13" endLine="18" endColumn="24" document="1"/> <entry offset="0x3c" hidden="true" document="1"/> <entry offset="0x3e" startLine="19" startColumn="9" endLine="19" endColumn="16" document="1"/> <entry offset="0x3f" startLine="20" startColumn="17" endLine="20" endColumn="34" document="1"/> <entry offset="0x46" startLine="21" startColumn="13" endLine="21" endColumn="33" document="1"/> <entry offset="0x4e" startLine="22" startColumn="9" endLine="22" endColumn="16" document="1"/> <entry offset="0x4f" startLine="24" startColumn="9" endLine="24" endColumn="29" document="1"/> <entry offset="0x56" startLine="26" startColumn="5" endLine="26" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x57"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> <local name="x" il_index="0" il_start="0x0" il_end="0x57" attributes="0"/> <scope startOffset="0x4" endOffset="0x1a"> <local name="y" il_index="1" il_start="0x4" il_end="0x1a" attributes="0"/> </scope> <scope startOffset="0x1d" endOffset="0x3b"> <local name="ex" il_index="3" il_start="0x1d" il_end="0x3b" attributes="0"/> <scope startOffset="0x25" endOffset="0x3b"> <local name="z" il_index="4" il_start="0x25" il_end="0x3b" attributes="0"/> </scope> </scope> <scope startOffset="0x3f" endOffset="0x4c"> <local name="q" il_index="5" il_start="0x3f" il_end="0x4c" attributes="0"/> </scope> </scope> </method> </methods> </symbols>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub TryCatchWhen_Debug() Dim source = <compilation> <file> Option Strict On Imports System Module M1 Public Sub Main() Dim x As Integer = 0 Try Dim y As String = "y" label1: label2: x = x \ x Catch ex As Exception When ex.Message IsNot Nothing Dim z As String = "z" Console.WriteLine(x) x = 1 GoTo label1 Finally Dim q As String = "q" Console.WriteLine(x) End Try Console.WriteLine(x) End Sub End Module </file> </compilation> Dim v = CompileAndVerify(CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe)) v.VerifyIL("M1.Main", " { // Code size 104 (0x68) .maxstack 2 .locals init (Integer V_0, //x String V_1, //y System.Exception V_2, //ex Boolean V_3, String V_4, //z String V_5) //q -IL_0000: nop -IL_0001: ldc.i4.0 IL_0002: stloc.0 .try { .try { -IL_0003: nop -IL_0004: ldstr ""y"" IL_0009: stloc.1 -IL_000a: nop -IL_000b: nop -IL_000c: ldloc.0 IL_000d: ldloc.0 IL_000e: div IL_000f: stloc.0 IL_0010: leave.s IL_004d } filter { ~IL_0012: isinst ""System.Exception"" IL_0017: dup IL_0018: brtrue.s IL_001e IL_001a: pop IL_001b: ldc.i4.0 IL_001c: br.s IL_0033 IL_001e: dup IL_001f: call ""Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)"" IL_0024: stloc.2 -IL_0025: ldloc.2 IL_0026: callvirt ""Function System.Exception.get_Message() As String"" IL_002b: ldnull IL_002c: cgt.un IL_002e: stloc.3 ~IL_002f: ldloc.3 IL_0030: ldc.i4.0 IL_0031: cgt.un IL_0033: endfilter } // end filter { // handler ~IL_0035: pop -IL_0036: ldstr ""z"" IL_003b: stloc.s V_4 -IL_003d: ldloc.0 IL_003e: call ""Sub System.Console.WriteLine(Integer)"" IL_0043: nop -IL_0044: ldc.i4.1 IL_0045: stloc.0 -IL_0046: call ""Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()"" IL_004b: leave.s IL_000a } ~IL_004d: leave.s IL_005f } finally { -IL_004f: nop -IL_0050: ldstr ""q"" IL_0055: stloc.s V_5 -IL_0057: ldloc.0 IL_0058: call ""Sub System.Console.WriteLine(Integer)"" IL_005d: nop IL_005e: endfinally } -IL_005f: nop -IL_0060: ldloc.0 IL_0061: call ""Sub System.Console.WriteLine(Integer)"" IL_0066: nop -IL_0067: ret } ", sequencePoints:="M1.Main") v.VerifyPdb("M1.Main", <symbols> <files> <file id="1" name="" language="VB"/> </files> <entryPoint declaringType="M1" methodName="Main"/> <methods> <method containingType="M1" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> <slot kind="0" offset="51"/> <slot kind="0" offset="119"/> <slot kind="1" offset="141"/> <slot kind="0" offset="188"/> <slot kind="0" offset="318"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="5" startColumn="5" endLine="5" endColumn="22" document="1"/> <entry offset="0x1" startLine="6" startColumn="13" endLine="6" endColumn="29" document="1"/> <entry offset="0x3" startLine="7" startColumn="9" endLine="7" endColumn="12" document="1"/> <entry offset="0x4" startLine="8" startColumn="17" endLine="8" endColumn="34" document="1"/> <entry offset="0xa" startLine="9" startColumn="1" endLine="9" endColumn="8" document="1"/> <entry offset="0xb" startLine="10" startColumn="1" endLine="10" endColumn="8" document="1"/> <entry offset="0xc" startLine="11" startColumn="13" endLine="11" endColumn="22" document="1"/> <entry offset="0x12" hidden="true" document="1"/> <entry offset="0x25" startLine="12" startColumn="9" endLine="12" endColumn="60" document="1"/> <entry offset="0x2f" hidden="true" document="1"/> <entry offset="0x35" hidden="true" document="1"/> <entry offset="0x36" startLine="13" startColumn="17" endLine="13" endColumn="34" document="1"/> <entry offset="0x3d" startLine="14" startColumn="13" endLine="14" endColumn="33" document="1"/> <entry offset="0x44" startLine="15" startColumn="13" endLine="15" endColumn="18" document="1"/> <entry offset="0x46" startLine="16" startColumn="13" endLine="16" endColumn="24" document="1"/> <entry offset="0x4d" hidden="true" document="1"/> <entry offset="0x4f" startLine="17" startColumn="9" endLine="17" endColumn="16" document="1"/> <entry offset="0x50" startLine="18" startColumn="17" endLine="18" endColumn="34" document="1"/> <entry offset="0x57" startLine="19" startColumn="13" endLine="19" endColumn="33" document="1"/> <entry offset="0x5f" startLine="20" startColumn="9" endLine="20" endColumn="16" document="1"/> <entry offset="0x60" startLine="22" startColumn="9" endLine="22" endColumn="29" document="1"/> <entry offset="0x67" startLine="24" startColumn="5" endLine="24" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x68"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> <local name="x" il_index="0" il_start="0x0" il_end="0x68" attributes="0"/> <scope startOffset="0x4" endOffset="0xf"> <local name="y" il_index="1" il_start="0x4" il_end="0xf" attributes="0"/> </scope> <scope startOffset="0x12" endOffset="0x4c"> <local name="ex" il_index="2" il_start="0x12" il_end="0x4c" attributes="0"/> <scope startOffset="0x36" endOffset="0x4c"> <local name="z" il_index="4" il_start="0x36" il_end="0x4c" attributes="0"/> </scope> </scope> <scope startOffset="0x50" endOffset="0x5d"> <local name="q" il_index="5" il_start="0x50" il_end="0x5d" attributes="0"/> </scope> </scope> </method> </methods> </symbols>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub TryCatchWhen_Release() Dim source = <compilation> <file> Imports System Imports System.IO Module M1 Function filter(e As Exception) Return True End Function Public Sub Main() Try Throw New InvalidOperationException() Catch e As IOException When filter(e) Console.WriteLine() Catch e As Exception When filter(e) Console.WriteLine() End Try End Sub End Module </file> </compilation> Dim v = CompileAndVerify(CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe)) v.VerifyIL("M1.Main", " { // Code size 103 (0x67) .maxstack 2 .locals init (System.IO.IOException V_0, //e System.Exception V_1) //e .try { -IL_0000: newobj ""Sub System.InvalidOperationException..ctor()"" IL_0005: throw } filter { ~IL_0006: isinst ""System.IO.IOException"" IL_000b: dup IL_000c: brtrue.s IL_0012 IL_000e: pop IL_000f: ldc.i4.0 IL_0010: br.s IL_0027 IL_0012: dup IL_0013: call ""Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)"" IL_0018: stloc.0 -IL_0019: ldloc.0 IL_001a: call ""Function M1.filter(System.Exception) As Object"" IL_001f: call ""Function Microsoft.VisualBasic.CompilerServices.Conversions.ToBoolean(Object) As Boolean"" IL_0024: ldc.i4.0 IL_0025: cgt.un IL_0027: endfilter } // end filter { // handler ~IL_0029: pop -IL_002a: call ""Sub System.Console.WriteLine()"" IL_002f: call ""Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()"" IL_0034: leave.s IL_0066 } filter { ~IL_0036: isinst ""System.Exception"" IL_003b: dup IL_003c: brtrue.s IL_0042 IL_003e: pop IL_003f: ldc.i4.0 IL_0040: br.s IL_0057 IL_0042: dup IL_0043: call ""Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)"" IL_0048: stloc.1 -IL_0049: ldloc.1 IL_004a: call ""Function M1.filter(System.Exception) As Object"" IL_004f: call ""Function Microsoft.VisualBasic.CompilerServices.Conversions.ToBoolean(Object) As Boolean"" IL_0054: ldc.i4.0 IL_0055: cgt.un IL_0057: endfilter } // end filter { // handler ~IL_0059: pop -IL_005a: call ""Sub System.Console.WriteLine()"" IL_005f: call ""Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()"" IL_0064: leave.s IL_0066 } -IL_0066: ret } ", sequencePoints:="M1.Main") End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub TestBasic1() Dim source = <compilation> <file><![CDATA[ Option Strict On Module Module1 Sub Main() Dim x As Integer = 3 Do While (x <= 3) Dim y As Integer = x + 1 x = y Loop End Sub End Module ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( source, TestOptions.DebugExe) compilation.VerifyPdb("Module1.Main", <symbols> <files> <file id="1" name="" language="VB"/> </files> <entryPoint declaringType="Module1" methodName="Main"/> <methods> <method containingType="Module1" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> <slot kind="0" offset="65"/> <slot kind="1" offset="30"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="4" startColumn="5" endLine="4" endColumn="15" document="1"/> <entry offset="0x1" startLine="5" startColumn="13" endLine="5" endColumn="29" document="1"/> <entry offset="0x3" hidden="true" document="1"/> <entry offset="0x5" startLine="7" startColumn="17" endLine="7" endColumn="37" document="1"/> <entry offset="0x9" startLine="8" startColumn="13" endLine="8" endColumn="18" document="1"/> <entry offset="0xb" startLine="9" startColumn="9" endLine="9" endColumn="13" document="1"/> <entry offset="0xc" startLine="6" startColumn="9" endLine="6" endColumn="26" document="1"/> <entry offset="0x14" hidden="true" document="1"/> <entry offset="0x17" startLine="10" startColumn="5" endLine="10" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x18"> <currentnamespace name=""/> <local name="x" il_index="0" il_start="0x0" il_end="0x18" attributes="0"/> <scope startOffset="0x5" endOffset="0xb"> <local name="y" il_index="1" il_start="0x5" il_end="0xb" attributes="0"/> </scope> </scope> </method> </methods> </symbols>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub TestBasicCtor() Dim source = <compilation> <file><![CDATA[ Class C1 Sub New() System.Console.WriteLine("Hello, world.") End Sub End Class ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugDll) compilation.VerifyPdb("C1..ctor", <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="C1" name=".ctor"> <sequencePoints> <entry offset="0x0" startLine="2" startColumn="5" endLine="2" endColumn="14" document="1"/> <entry offset="0x8" startLine="3" startColumn="9" endLine="3" endColumn="50" document="1"/> <entry offset="0x13" startLine="4" startColumn="5" endLine="4" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x14"> <currentnamespace name=""/> </scope> </method> </methods> </symbols>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub TestLabels() Dim source = <compilation> <file><![CDATA[ Class C1 Sub New() label1: label2: label3: goto label2: End Sub End Class ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugDll) compilation.VerifyPdb("C1..ctor", <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="C1" name=".ctor"> <sequencePoints> <entry offset="0x0" startLine="2" startColumn="5" endLine="2" endColumn="14" document="1"/> <entry offset="0x8" startLine="3" startColumn="9" endLine="3" endColumn="16" document="1"/> <entry offset="0x9" startLine="4" startColumn="9" endLine="4" endColumn="16" document="1"/> <entry offset="0xa" startLine="5" startColumn="9" endLine="5" endColumn="16" document="1"/> <entry offset="0xb" startLine="7" startColumn="9" endLine="7" endColumn="20" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0xd"> <currentnamespace name=""/> </scope> </method> </methods> </symbols>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub IfStatement() Dim source = <compilation> <file><![CDATA[ Imports System Class C Sub F() If G() Then Console.WriteLine(1) Else Console.WriteLine(2) End If Console.WriteLine(3) End Sub Function G() As Boolean Return False End Function End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugDll) Dim v = CompileAndVerify(compilation) v.VerifyIL("C.F", " { // Code size 38 (0x26) .maxstack 1 .locals init (Boolean V_0) -IL_0000: nop -IL_0001: ldarg.0 IL_0002: call ""Function C.G() As Boolean"" IL_0007: stloc.0 ~IL_0008: ldloc.0 IL_0009: brfalse.s IL_0015 -IL_000b: ldc.i4.1 IL_000c: call ""Sub System.Console.WriteLine(Integer)"" IL_0011: nop -IL_0012: nop IL_0013: br.s IL_001e -IL_0015: nop -IL_0016: ldc.i4.2 IL_0017: call ""Sub System.Console.WriteLine(Integer)"" IL_001c: nop -IL_001d: nop -IL_001e: ldc.i4.3 IL_001f: call ""Sub System.Console.WriteLine(Integer)"" IL_0024: nop -IL_0025: ret } ", sequencePoints:="C.F") v.VerifyPdb("C.F", <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="C" name="F"> <customDebugInfo> <encLocalSlotMap> <slot kind="1" offset="0"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="4" startColumn="5" endLine="4" endColumn="12" document="1"/> <entry offset="0x1" startLine="5" startColumn="9" endLine="5" endColumn="20" document="1"/> <entry offset="0x8" hidden="true" document="1"/> <entry offset="0xb" startLine="6" startColumn="13" endLine="6" endColumn="33" document="1"/> <entry offset="0x12" startLine="9" startColumn="9" endLine="9" endColumn="15" document="1"/> <entry offset="0x15" startLine="7" startColumn="9" endLine="7" endColumn="13" document="1"/> <entry offset="0x16" startLine="8" startColumn="13" endLine="8" endColumn="33" document="1"/> <entry offset="0x1d" startLine="9" startColumn="9" endLine="9" endColumn="15" document="1"/> <entry offset="0x1e" startLine="11" startColumn="9" endLine="11" endColumn="29" document="1"/> <entry offset="0x25" startLine="12" startColumn="5" endLine="12" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x26"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> </scope> </method> </methods> </symbols>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub DoWhileStatement() Dim source = <compilation> <file><![CDATA[ Imports System Class C Sub F() Do While G() Console.WriteLine(1) Loop End Sub Function G() As Boolean Return False End Function End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugDll) Dim v = CompileAndVerify(compilation) v.VerifyIL("C.F", " { // Code size 22 (0x16) .maxstack 1 .locals init (Boolean V_0) -IL_0000: nop ~IL_0001: br.s IL_000b -IL_0003: ldc.i4.1 IL_0004: call ""Sub System.Console.WriteLine(Integer)"" IL_0009: nop -IL_000a: nop -IL_000b: ldarg.0 IL_000c: call ""Function C.G() As Boolean"" IL_0011: stloc.0 ~IL_0012: ldloc.0 IL_0013: brtrue.s IL_0003 -IL_0015: ret } ", sequencePoints:="C.F") v.VerifyPdb("C.F", <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="C" name="F"> <customDebugInfo> <encLocalSlotMap> <slot kind="1" offset="0"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="4" startColumn="5" endLine="4" endColumn="12" document="1"/> <entry offset="0x1" hidden="true" document="1"/> <entry offset="0x3" startLine="6" startColumn="13" endLine="6" endColumn="33" document="1"/> <entry offset="0xa" startLine="7" startColumn="9" endLine="7" endColumn="13" document="1"/> <entry offset="0xb" startLine="5" startColumn="9" endLine="5" endColumn="21" document="1"/> <entry offset="0x12" hidden="true" document="1"/> <entry offset="0x15" startLine="8" startColumn="5" endLine="8" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x16"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> </scope> </method> </methods> </symbols>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub DoLoopWhileStatement() Dim source = <compilation> <file><![CDATA[ Imports System Class C Sub F() Do Console.WriteLine(1) Loop While G() End Sub Function G() As Boolean Return False End Function End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugDll) Dim v = CompileAndVerify(compilation) v.VerifyIL("C.F", " { // Code size 21 (0x15) .maxstack 1 .locals init (Boolean V_0) -IL_0000: nop -IL_0001: nop -IL_0002: ldc.i4.1 IL_0003: call ""Sub System.Console.WriteLine(Integer)"" IL_0008: nop -IL_0009: nop IL_000a: ldarg.0 IL_000b: call ""Function C.G() As Boolean"" IL_0010: stloc.0 ~IL_0011: ldloc.0 IL_0012: brtrue.s IL_0001 -IL_0014: ret } ", sequencePoints:="C.F") v.VerifyPdb("C.F", <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="C" name="F"> <customDebugInfo> <encLocalSlotMap> <slot kind="1" offset="0"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="4" startColumn="5" endLine="4" endColumn="12" document="1"/> <entry offset="0x1" startLine="5" startColumn="9" endLine="5" endColumn="11" document="1"/> <entry offset="0x2" startLine="6" startColumn="13" endLine="6" endColumn="33" document="1"/> <entry offset="0x9" startLine="7" startColumn="9" endLine="7" endColumn="23" document="1"/> <entry offset="0x11" hidden="true" document="1"/> <entry offset="0x14" startLine="8" startColumn="5" endLine="8" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x15"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> </scope> </method> </methods> </symbols>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub ForStatement() Dim source = <compilation> <file><![CDATA[ Imports System Class C Sub F() For a = G(0) To G(1) Step G(2) Console.WriteLine(1) Next End Sub Function G(a As Integer) As Integer Return 10 End Function End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugDll) Dim v = CompileAndVerify(compilation) v.VerifyIL("C.F", " { // Code size 55 (0x37) .maxstack 3 .locals init (Integer V_0, Integer V_1, Integer V_2, Integer V_3) //a -IL_0000: nop -IL_0001: ldarg.0 IL_0002: ldc.i4.0 IL_0003: call ""Function C.G(Integer) As Integer"" IL_0008: stloc.0 IL_0009: ldarg.0 IL_000a: ldc.i4.1 IL_000b: call ""Function C.G(Integer) As Integer"" IL_0010: stloc.1 IL_0011: ldarg.0 IL_0012: ldc.i4.2 IL_0013: call ""Function C.G(Integer) As Integer"" IL_0018: stloc.2 IL_0019: ldloc.0 IL_001a: stloc.3 ~IL_001b: br.s IL_0028 -IL_001d: ldc.i4.1 IL_001e: call ""Sub System.Console.WriteLine(Integer)"" IL_0023: nop -IL_0024: ldloc.3 IL_0025: ldloc.2 IL_0026: add.ovf IL_0027: stloc.3 ~IL_0028: ldloc.2 IL_0029: ldc.i4.s 31 IL_002b: shr IL_002c: ldloc.3 IL_002d: xor IL_002e: ldloc.2 IL_002f: ldc.i4.s 31 IL_0031: shr IL_0032: ldloc.1 IL_0033: xor IL_0034: ble.s IL_001d -IL_0036: ret }", sequencePoints:="C.F") v.VerifyPdb("C.F", <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="C" name="F"> <customDebugInfo> <encLocalSlotMap> <slot kind="13" offset="0"/> <slot kind="11" offset="0"/> <slot kind="12" offset="0"/> <slot kind="0" offset="0"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="4" startColumn="5" endLine="4" endColumn="12" document="1"/> <entry offset="0x1" startLine="5" startColumn="9" endLine="5" endColumn="39" document="1"/> <entry offset="0x1b" hidden="true" document="1"/> <entry offset="0x1d" startLine="6" startColumn="13" endLine="6" endColumn="33" document="1"/> <entry offset="0x24" startLine="7" startColumn="9" endLine="7" endColumn="13" document="1"/> <entry offset="0x28" hidden="true" document="1"/> <entry offset="0x36" startLine="8" startColumn="5" endLine="8" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x37"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> <scope startOffset="0x1" endOffset="0x35"> <local name="a" il_index="3" il_start="0x1" il_end="0x35" attributes="0"/> </scope> </scope> </method> </methods> </symbols>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub ForStatement_LateBound() Dim v = CompileAndVerify( <compilation> <file name="a.vb"> Option Strict On Public Class MyClass1 Public Shared Sub Main() Dim ctrlVar As Object Dim initValue As Object = 0 Dim limit As Object = 2 Dim stp As Object = 1 For ctrlVar = initValue To limit Step stp System.Console.WriteLine(ctrlVar) Next End Sub End Class </file> </compilation>, options:=TestOptions.DebugDll) v.VerifyIL("MyClass1.Main", " { // Code size 70 (0x46) .maxstack 6 .locals init (Object V_0, //ctrlVar Object V_1, //initValue Object V_2, //limit Object V_3, //stp Object V_4, Boolean V_5, Boolean V_6) -IL_0000: nop -IL_0001: ldc.i4.0 IL_0002: box ""Integer"" IL_0007: stloc.1 -IL_0008: ldc.i4.2 IL_0009: box ""Integer"" IL_000e: stloc.2 -IL_000f: ldc.i4.1 IL_0010: box ""Integer"" IL_0015: stloc.3 -IL_0016: ldloc.0 IL_0017: ldloc.1 IL_0018: ldloc.2 IL_0019: ldloc.3 IL_001a: ldloca.s V_4 IL_001c: ldloca.s V_0 IL_001e: call ""Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForLoopInitObj(Object, Object, Object, Object, ByRef Object, ByRef Object) As Boolean"" IL_0023: stloc.s V_5 ~IL_0025: ldloc.s V_5 IL_0027: brfalse.s IL_0045 -IL_0029: ldloc.0 IL_002a: call ""Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"" IL_002f: call ""Sub System.Console.WriteLine(Object)"" IL_0034: nop -IL_0035: ldloc.0 IL_0036: ldloc.s V_4 IL_0038: ldloca.s V_0 IL_003a: call ""Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForNextCheckObj(Object, Object, ByRef Object) As Boolean"" IL_003f: stloc.s V_6 ~IL_0041: ldloc.s V_6 IL_0043: brtrue.s IL_0029 -IL_0045: ret } ", sequencePoints:="MyClass1.Main") v.VerifyPdb("MyClass1.Main", <symbols> <files> <file id="1" name="a.vb" language="VB" checksumAlgorithm="SHA1" checksum="87-56-72-A9-63-E5-5D-0C-F3-97-85-44-CF-51-55-8E-76-E7-1D-F1"/> </files> <methods> <method containingType="MyClass1" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> <slot kind="0" offset="35"/> <slot kind="0" offset="72"/> <slot kind="0" offset="105"/> <slot kind="13" offset="134"/> <slot kind="1" offset="134"/> <slot kind="1" offset="134" ordinal="1"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="3" startColumn="5" endLine="3" endColumn="29" document="1"/> <entry offset="0x1" startLine="6" startColumn="13" endLine="6" endColumn="36" document="1"/> <entry offset="0x8" startLine="7" startColumn="13" endLine="7" endColumn="32" document="1"/> <entry offset="0xf" startLine="8" startColumn="13" endLine="8" endColumn="30" document="1"/> <entry offset="0x16" startLine="10" startColumn="9" endLine="10" endColumn="50" document="1"/> <entry offset="0x25" hidden="true" document="1"/> <entry offset="0x29" startLine="11" startColumn="13" endLine="11" endColumn="46" document="1"/> <entry offset="0x35" startLine="12" startColumn="9" endLine="12" endColumn="13" document="1"/> <entry offset="0x41" hidden="true" document="1"/> <entry offset="0x45" startLine="14" startColumn="5" endLine="14" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x46"> <currentnamespace name=""/> <local name="ctrlVar" il_index="0" il_start="0x0" il_end="0x46" attributes="0"/> <local name="initValue" il_index="1" il_start="0x0" il_end="0x46" attributes="0"/> <local name="limit" il_index="2" il_start="0x0" il_end="0x46" attributes="0"/> <local name="stp" il_index="3" il_start="0x0" il_end="0x46" attributes="0"/> </scope> </method> </methods> </symbols>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub SelectCaseStatement() Dim source = <compilation> <file><![CDATA[ Imports System Class C Sub F() Select Case G(1) Case G(2) Console.WriteLine(4) Case G(3) Console.WriteLine(5) End Select End Sub Function G(a As Integer) As Integer Return a End Function End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugDll) Dim v = CompileAndVerify(compilation) v.VerifyIL("C.F", " { // Code size 56 (0x38) .maxstack 3 .locals init (Integer V_0, Boolean V_1) -IL_0000: nop -IL_0001: nop IL_0002: ldarg.0 IL_0003: ldc.i4.1 IL_0004: call ""Function C.G(Integer) As Integer"" IL_0009: stloc.0 -IL_000a: ldloc.0 IL_000b: ldarg.0 IL_000c: ldc.i4.2 IL_000d: call ""Function C.G(Integer) As Integer"" IL_0012: ceq IL_0014: stloc.1 ~IL_0015: ldloc.1 IL_0016: brfalse.s IL_0021 -IL_0018: ldc.i4.4 IL_0019: call ""Sub System.Console.WriteLine(Integer)"" IL_001e: nop IL_001f: br.s IL_0036 -IL_0021: ldloc.0 IL_0022: ldarg.0 IL_0023: ldc.i4.3 IL_0024: call ""Function C.G(Integer) As Integer"" IL_0029: ceq IL_002b: stloc.1 ~IL_002c: ldloc.1 IL_002d: brfalse.s IL_0036 -IL_002f: ldc.i4.5 IL_0030: call ""Sub System.Console.WriteLine(Integer)"" IL_0035: nop -IL_0036: nop -IL_0037: ret } ", sequencePoints:="C.F") v.VerifyPdb("C.F", <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="C" name="F"> <customDebugInfo> <encLocalSlotMap> <slot kind="15" offset="0"/> <slot kind="1" offset="0"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="4" startColumn="5" endLine="4" endColumn="12" document="1"/> <entry offset="0x1" startLine="5" startColumn="9" endLine="5" endColumn="25" document="1"/> <entry offset="0xa" startLine="6" startColumn="13" endLine="6" endColumn="22" document="1"/> <entry offset="0x15" hidden="true" document="1"/> <entry offset="0x18" startLine="7" startColumn="17" endLine="7" endColumn="37" document="1"/> <entry offset="0x21" startLine="8" startColumn="13" endLine="8" endColumn="22" document="1"/> <entry offset="0x2c" hidden="true" document="1"/> <entry offset="0x2f" startLine="9" startColumn="17" endLine="9" endColumn="37" document="1"/> <entry offset="0x36" startLine="10" startColumn="9" endLine="10" endColumn="19" document="1"/> <entry offset="0x37" startLine="11" startColumn="5" endLine="11" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x38"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> </scope> </method> </methods> </symbols>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub TestIfThenAndBlocks() Dim source = <compilation> <file><![CDATA[ Imports System Module Module1 Sub Main(args As String()) Dim x As Integer = 0, xx = New Integer() If x < 10 Then Dim s As String = "hi" : Console.WriteLine(s) Else Console.WriteLine("bye") : Console.WriteLine("bye1") If x > 10 Then Console.WriteLine("hi") : Console.WriteLine("hi1") Else Dim s As String = "bye" : Console.WriteLine(s) Do While x < 5 If x < 1 Then Console.WriteLine("<1") ElseIf x < 2 Then Dim s2 As String = "<2" Console.WriteLine(s2) ElseIf x < 3 Then Dim s3 As String = "<3" Console.WriteLine(s3) Else Dim e1 As String = "Else" Console.WriteLine(e1) End If Dim newX As Integer = x + 1 x = newX Loop End Sub End Module ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe) compilation.VerifyPdb("Module1.Main", <symbols> <files> <file id="1" name="" language="VB"/> </files> <entryPoint declaringType="Module1" methodName="Main" parameterNames="args"/> <methods> <method containingType="Module1" name="Main" parameterNames="args"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> <slot kind="0" offset="22"/> <slot kind="1" offset="52"/> <slot kind="0" offset="71"/> <slot kind="1" offset="180"/> <slot kind="0" offset="255"/> <slot kind="0" offset="753"/> <slot kind="1" offset="337"/> <slot kind="1" offset="405"/> <slot kind="0" offset="444"/> <slot kind="1" offset="516"/> <slot kind="0" offset="555"/> <slot kind="0" offset="653"/> <slot kind="1" offset="309"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="4" startColumn="5" endLine="4" endColumn="31" document="1"/> <entry offset="0x1" startLine="6" startColumn="13" endLine="6" endColumn="29" document="1"/> <entry offset="0x3" startLine="6" startColumn="31" endLine="6" endColumn="49" document="1"/> <entry offset="0xb" startLine="8" startColumn="9" endLine="8" endColumn="23" document="1"/> <entry offset="0x11" hidden="true" document="1"/> <entry offset="0x14" startLine="8" startColumn="28" endLine="8" endColumn="46" document="1"/> <entry offset="0x1a" startLine="8" startColumn="49" endLine="8" endColumn="69" document="1"/> <entry offset="0x23" startLine="8" startColumn="70" endLine="8" endColumn="74" document="1"/> <entry offset="0x24" startLine="8" startColumn="75" endLine="8" endColumn="99" document="1"/> <entry offset="0x2f" startLine="8" startColumn="102" endLine="8" endColumn="127" document="1"/> <entry offset="0x3a" startLine="9" startColumn="9" endLine="9" endColumn="23" document="1"/> <entry offset="0x41" hidden="true" document="1"/> <entry offset="0x45" startLine="9" startColumn="24" endLine="9" endColumn="47" document="1"/> <entry offset="0x50" startLine="9" startColumn="50" endLine="9" endColumn="74" document="1"/> <entry offset="0x5d" startLine="9" startColumn="75" endLine="9" endColumn="79" document="1"/> <entry offset="0x5e" startLine="9" startColumn="84" endLine="9" endColumn="103" document="1"/> <entry offset="0x65" startLine="9" startColumn="106" endLine="9" endColumn="126" document="1"/> <entry offset="0x6d" hidden="true" document="1"/> <entry offset="0x6f" startLine="12" startColumn="13" endLine="12" endColumn="26" document="1"/> <entry offset="0x75" hidden="true" document="1"/> <entry offset="0x79" startLine="13" startColumn="17" endLine="13" endColumn="40" document="1"/> <entry offset="0x84" startLine="23" startColumn="13" endLine="23" endColumn="19" document="1"/> <entry offset="0x87" startLine="14" startColumn="13" endLine="14" endColumn="30" document="1"/> <entry offset="0x8d" hidden="true" document="1"/> <entry offset="0x91" startLine="15" startColumn="21" endLine="15" endColumn="40" document="1"/> <entry offset="0x98" startLine="16" startColumn="17" endLine="16" endColumn="38" document="1"/> <entry offset="0xa0" startLine="23" startColumn="13" endLine="23" endColumn="19" document="1"/> <entry offset="0xa3" startLine="17" startColumn="13" endLine="17" endColumn="30" document="1"/> <entry offset="0xa9" hidden="true" document="1"/> <entry offset="0xad" startLine="18" startColumn="21" endLine="18" endColumn="40" document="1"/> <entry offset="0xb4" startLine="19" startColumn="17" endLine="19" endColumn="38" document="1"/> <entry offset="0xbc" startLine="23" startColumn="13" endLine="23" endColumn="19" document="1"/> <entry offset="0xbf" startLine="20" startColumn="13" endLine="20" endColumn="17" document="1"/> <entry offset="0xc0" startLine="21" startColumn="21" endLine="21" endColumn="42" document="1"/> <entry offset="0xc7" startLine="22" startColumn="17" endLine="22" endColumn="38" document="1"/> <entry offset="0xcf" startLine="23" startColumn="13" endLine="23" endColumn="19" document="1"/> <entry offset="0xd0" startLine="25" startColumn="17" endLine="25" endColumn="40" document="1"/> <entry offset="0xd5" startLine="26" startColumn="13" endLine="26" endColumn="21" document="1"/> <entry offset="0xd8" startLine="27" startColumn="9" endLine="27" endColumn="13" document="1"/> <entry offset="0xd9" startLine="11" startColumn="9" endLine="11" endColumn="23" document="1"/> <entry offset="0xdf" hidden="true" document="1"/> <entry offset="0xe3" startLine="29" startColumn="5" endLine="29" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0xe4"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> <local name="x" il_index="0" il_start="0x0" il_end="0xe4" attributes="0"/> <local name="xx" il_index="1" il_start="0x0" il_end="0xe4" attributes="0"/> <scope startOffset="0x14" endOffset="0x20"> <local name="s" il_index="3" il_start="0x14" il_end="0x20" attributes="0"/> </scope> <scope startOffset="0x5e" endOffset="0x6c"> <local name="s" il_index="5" il_start="0x5e" il_end="0x6c" attributes="0"/> </scope> <scope startOffset="0x6f" endOffset="0xd8"> <local name="newX" il_index="6" il_start="0x6f" il_end="0xd8" attributes="0"/> <scope startOffset="0x91" endOffset="0xa0"> <local name="s2" il_index="9" il_start="0x91" il_end="0xa0" attributes="0"/> </scope> <scope startOffset="0xad" endOffset="0xbc"> <local name="s3" il_index="11" il_start="0xad" il_end="0xbc" attributes="0"/> </scope> <scope startOffset="0xc0" endOffset="0xcf"> <local name="e1" il_index="12" il_start="0xc0" il_end="0xcf" attributes="0"/> </scope> </scope> </scope> </method> </methods> </symbols>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub TestTopConditionDoLoop() Dim source = <compilation> <file><![CDATA[ Imports System Module Module1 Sub Main(args As String()) Dim x As Integer = 0 Do While x < 5 If x < 1 Then Console.WriteLine("<1") ElseIf x < 2 Then Dim s2 As String = "<2" Console.WriteLine(s2) ElseIf x < 3 Then Dim s3 As String = "<3" Console.WriteLine(s3) Else Dim e1 As String = "Else" Console.WriteLine(e1) End If Dim newX As Integer = x + 1 x = newX Loop End Sub End Module ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe) compilation.VerifyPdb("Module1.Main", <symbols> <files> <file id="1" name="" language="VB"/> </files> <entryPoint declaringType="Module1" methodName="Main" parameterNames="args"/> <methods> <method containingType="Module1" name="Main" parameterNames="args"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> <slot kind="0" offset="474"/> <slot kind="1" offset="58"/> <slot kind="1" offset="126"/> <slot kind="0" offset="165"/> <slot kind="1" offset="237"/> <slot kind="0" offset="276"/> <slot kind="0" offset="374"/> <slot kind="1" offset="30"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="4" startColumn="5" endLine="4" endColumn="31" document="1"/> <entry offset="0x1" startLine="6" startColumn="13" endLine="6" endColumn="29" document="1"/> <entry offset="0x3" hidden="true" document="1"/> <entry offset="0x5" startLine="8" startColumn="13" endLine="8" endColumn="26" document="1"/> <entry offset="0xa" hidden="true" document="1"/> <entry offset="0xd" startLine="9" startColumn="17" endLine="9" endColumn="40" document="1"/> <entry offset="0x18" startLine="19" startColumn="13" endLine="19" endColumn="19" document="1"/> <entry offset="0x1b" startLine="10" startColumn="13" endLine="10" endColumn="30" document="1"/> <entry offset="0x20" hidden="true" document="1"/> <entry offset="0x23" startLine="11" startColumn="21" endLine="11" endColumn="40" document="1"/> <entry offset="0x2a" startLine="12" startColumn="17" endLine="12" endColumn="38" document="1"/> <entry offset="0x32" startLine="19" startColumn="13" endLine="19" endColumn="19" document="1"/> <entry offset="0x35" startLine="13" startColumn="13" endLine="13" endColumn="30" document="1"/> <entry offset="0x3b" hidden="true" document="1"/> <entry offset="0x3f" startLine="14" startColumn="21" endLine="14" endColumn="40" document="1"/> <entry offset="0x46" startLine="15" startColumn="17" endLine="15" endColumn="38" document="1"/> <entry offset="0x4e" startLine="19" startColumn="13" endLine="19" endColumn="19" document="1"/> <entry offset="0x51" startLine="16" startColumn="13" endLine="16" endColumn="17" document="1"/> <entry offset="0x52" startLine="17" startColumn="21" endLine="17" endColumn="42" document="1"/> <entry offset="0x59" startLine="18" startColumn="17" endLine="18" endColumn="38" document="1"/> <entry offset="0x61" startLine="19" startColumn="13" endLine="19" endColumn="19" document="1"/> <entry offset="0x62" startLine="21" startColumn="17" endLine="21" endColumn="40" document="1"/> <entry offset="0x66" startLine="22" startColumn="13" endLine="22" endColumn="21" document="1"/> <entry offset="0x68" startLine="23" startColumn="9" endLine="23" endColumn="13" document="1"/> <entry offset="0x69" startLine="7" startColumn="9" endLine="7" endColumn="23" document="1"/> <entry offset="0x6f" hidden="true" document="1"/> <entry offset="0x73" startLine="25" startColumn="5" endLine="25" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x74"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> <local name="x" il_index="0" il_start="0x0" il_end="0x74" attributes="0"/> <scope startOffset="0x5" endOffset="0x68"> <local name="newX" il_index="1" il_start="0x5" il_end="0x68" attributes="0"/> <scope startOffset="0x23" endOffset="0x32"> <local name="s2" il_index="4" il_start="0x23" il_end="0x32" attributes="0"/> </scope> <scope startOffset="0x3f" endOffset="0x4e"> <local name="s3" il_index="6" il_start="0x3f" il_end="0x4e" attributes="0"/> </scope> <scope startOffset="0x52" endOffset="0x61"> <local name="e1" il_index="7" il_start="0x52" il_end="0x61" attributes="0"/> </scope> </scope> </scope> </method> </methods> </symbols>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub TestBottomConditionDoLoop() Dim source = <compilation> <file><![CDATA[ Imports System Module Module1 Sub Main(args As String()) Dim x As Integer = 0 Do If x < 1 Then Console.WriteLine("<1") ElseIf x < 2 Then Dim s2 As String = "<2" Console.WriteLine(s2) ElseIf x < 3 Then Dim s3 As String = "<3" Console.WriteLine(s3) Else Dim e1 As String = "Else" Console.WriteLine(e1) End If Dim newX As Integer = x + 1 x = newX Loop While x < 5 End Sub End Module ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( source, TestOptions.DebugExe) compilation.VerifyPdb("Module1.Main", <symbols> <files> <file id="1" name="" language="VB"/> </files> <entryPoint declaringType="Module1" methodName="Main" parameterNames="args"/> <methods> <method containingType="Module1" name="Main" parameterNames="args"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> <slot kind="0" offset="464"/> <slot kind="1" offset="48"/> <slot kind="1" offset="116"/> <slot kind="0" offset="155"/> <slot kind="1" offset="227"/> <slot kind="0" offset="266"/> <slot kind="0" offset="364"/> <slot kind="1" offset="32"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="4" startColumn="5" endLine="4" endColumn="31" document="1"/> <entry offset="0x1" startLine="6" startColumn="13" endLine="6" endColumn="29" document="1"/> <entry offset="0x3" startLine="8" startColumn="9" endLine="8" endColumn="11" document="1"/> <entry offset="0x4" startLine="9" startColumn="13" endLine="9" endColumn="26" document="1"/> <entry offset="0x9" hidden="true" document="1"/> <entry offset="0xc" startLine="10" startColumn="17" endLine="10" endColumn="40" document="1"/> <entry offset="0x17" startLine="20" startColumn="13" endLine="20" endColumn="19" document="1"/> <entry offset="0x1a" startLine="11" startColumn="13" endLine="11" endColumn="30" document="1"/> <entry offset="0x1f" hidden="true" document="1"/> <entry offset="0x22" startLine="12" startColumn="21" endLine="12" endColumn="40" document="1"/> <entry offset="0x29" startLine="13" startColumn="17" endLine="13" endColumn="38" document="1"/> <entry offset="0x31" startLine="20" startColumn="13" endLine="20" endColumn="19" document="1"/> <entry offset="0x34" startLine="14" startColumn="13" endLine="14" endColumn="30" document="1"/> <entry offset="0x3a" hidden="true" document="1"/> <entry offset="0x3e" startLine="15" startColumn="21" endLine="15" endColumn="40" document="1"/> <entry offset="0x45" startLine="16" startColumn="17" endLine="16" endColumn="38" document="1"/> <entry offset="0x4d" startLine="20" startColumn="13" endLine="20" endColumn="19" document="1"/> <entry offset="0x50" startLine="17" startColumn="13" endLine="17" endColumn="17" document="1"/> <entry offset="0x51" startLine="18" startColumn="21" endLine="18" endColumn="42" document="1"/> <entry offset="0x58" startLine="19" startColumn="17" endLine="19" endColumn="38" document="1"/> <entry offset="0x60" startLine="20" startColumn="13" endLine="20" endColumn="19" document="1"/> <entry offset="0x61" startLine="22" startColumn="17" endLine="22" endColumn="40" document="1"/> <entry offset="0x65" startLine="23" startColumn="13" endLine="23" endColumn="21" document="1"/> <entry offset="0x67" startLine="24" startColumn="9" endLine="24" endColumn="25" document="1"/> <entry offset="0x6e" hidden="true" document="1"/> <entry offset="0x72" startLine="26" startColumn="5" endLine="26" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x73"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> <local name="x" il_index="0" il_start="0x0" il_end="0x73" attributes="0"/> <scope startOffset="0x4" endOffset="0x67"> <local name="newX" il_index="1" il_start="0x4" il_end="0x67" attributes="0"/> <scope startOffset="0x22" endOffset="0x31"> <local name="s2" il_index="4" il_start="0x22" il_end="0x31" attributes="0"/> </scope> <scope startOffset="0x3e" endOffset="0x4d"> <local name="s3" il_index="6" il_start="0x3e" il_end="0x4d" attributes="0"/> </scope> <scope startOffset="0x51" endOffset="0x60"> <local name="e1" il_index="7" il_start="0x51" il_end="0x60" attributes="0"/> </scope> </scope> </scope> </method> </methods> </symbols>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub TestInfiniteLoop() Dim source = <compilation> <file><![CDATA[ Imports System Module Module1 Sub Main(args As String()) Dim x As Integer = 0 Do Dim newX As Integer = x + 1 x = newX Loop End Sub End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe) compilation.VerifyPdb("Module1.Main", <symbols> <files> <file id="1" name="" language="VB"/> </files> <entryPoint declaringType="Module1" methodName="Main" parameterNames="args"/> <methods> <method containingType="Module1" name="Main" parameterNames="args"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> <slot kind="0" offset="52"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="4" startColumn="5" endLine="4" endColumn="31" document="1"/> <entry offset="0x1" startLine="6" startColumn="13" endLine="6" endColumn="29" document="1"/> <entry offset="0x3" startLine="8" startColumn="9" endLine="8" endColumn="11" document="1"/> <entry offset="0x4" startLine="9" startColumn="17" endLine="9" endColumn="40" document="1"/> <entry offset="0x8" startLine="10" startColumn="13" endLine="10" endColumn="21" document="1"/> <entry offset="0xa" startLine="11" startColumn="9" endLine="11" endColumn="13" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0xd"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> <local name="x" il_index="0" il_start="0x0" il_end="0xd" attributes="0"/> <scope startOffset="0x4" endOffset="0xa"> <local name="newX" il_index="1" il_start="0x4" il_end="0xa" attributes="0"/> </scope> </scope> </method> </methods> </symbols>) End Sub <WorkItem(527647, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527647")> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub ExtraSequencePointForEndIf() Dim source = <compilation> <file><![CDATA[ Imports System Public Module MyMod Public Sub Main(args As String()) If (args IsNot Nothing) Then Console.WriteLine("Then") Else Console.WriteLine("Else") End If End Sub End Module ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( source, TestOptions.DebugExe) ' By Design (better than Dev10): <entry offset="0x19" startLine="10" startColumn="9" endLine="10" endColumn="15" document="1"/> compilation.VerifyPdb("MyMod.Main", <symbols> <files> <file id="1" name="" language="VB"/> </files> <entryPoint declaringType="MyMod" methodName="Main" parameterNames="args"/> <methods> <method containingType="MyMod" name="Main" parameterNames="args"> <customDebugInfo> <encLocalSlotMap> <slot kind="1" offset="0"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="5" startColumn="5" endLine="5" endColumn="38" document="1"/> <entry offset="0x1" startLine="6" startColumn="9" endLine="6" endColumn="37" document="1"/> <entry offset="0x6" hidden="true" document="1"/> <entry offset="0x9" startLine="7" startColumn="13" endLine="7" endColumn="38" document="1"/> <entry offset="0x14" startLine="10" startColumn="9" endLine="10" endColumn="15" document="1"/> <entry offset="0x17" startLine="8" startColumn="9" endLine="8" endColumn="13" document="1"/> <entry offset="0x18" startLine="9" startColumn="13" endLine="9" endColumn="38" document="1"/> <entry offset="0x23" startLine="10" startColumn="9" endLine="10" endColumn="15" document="1"/> <entry offset="0x24" startLine="11" startColumn="5" endLine="11" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x25"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> </scope> </method> </methods> </symbols>) End Sub <WorkItem(538821, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538821")> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub MissingSequencePointForOptimizedIfThen() Dim source = <compilation> <file><![CDATA[ Imports System Public Module MyMod Public Sub Main() Console.WriteLine("B") If "x"c = "X"c Then Console.WriteLine("=") End If If "z"c <> "z"c Then Console.WriteLine("<>") End If Console.WriteLine("E") End Sub End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe) CompileAndVerify(compilation).VerifyIL("MyMod.Main", " { // Code size 34 (0x22) .maxstack 1 .locals init (Boolean V_0, Boolean V_1) -IL_0000: nop -IL_0001: ldstr ""B"" IL_0006: call ""Sub System.Console.WriteLine(String)"" IL_000b: nop -IL_000c: ldc.i4.0 IL_000d: stloc.0 IL_000e: br.s IL_0010 -IL_0010: nop -IL_0011: ldc.i4.0 IL_0012: stloc.1 IL_0013: br.s IL_0015 -IL_0015: nop -IL_0016: ldstr ""E"" IL_001b: call ""Sub System.Console.WriteLine(String)"" IL_0020: nop -IL_0021: ret } ", sequencePoints:="MyMod.Main") compilation.VerifyPdb("MyMod.Main", <symbols> <files> <file id="1" name="" language="VB"/> </files> <entryPoint declaringType="MyMod" methodName="Main"/> <methods> <method containingType="MyMod" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="1" offset="34"/> <slot kind="1" offset="117"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="5" startColumn="5" endLine="5" endColumn="22" document="1"/> <entry offset="0x1" startLine="6" startColumn="9" endLine="6" endColumn="31" document="1"/> <entry offset="0xc" startLine="8" startColumn="9" endLine="8" endColumn="28" document="1"/> <entry offset="0x10" startLine="10" startColumn="9" endLine="10" endColumn="15" document="1"/> <entry offset="0x11" startLine="12" startColumn="9" endLine="12" endColumn="29" document="1"/> <entry offset="0x15" startLine="14" startColumn="9" endLine="14" endColumn="15" document="1"/> <entry offset="0x16" startLine="16" startColumn="9" endLine="16" endColumn="31" document="1"/> <entry offset="0x21" startLine="17" startColumn="5" endLine="17" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x22"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> </scope> </method> </methods> </symbols>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub MissingSequencePointForTrivialIfThen() Dim source = <compilation> <file><![CDATA[ Imports System Module Module1 Sub Main() ' one If (False) Then Dim x As String = "hello" Show(x) End If ' two If (False) Then Show("hello") Try Catch ex As Exception Finally ' three If (False) Then Show("hello") End Try End Sub Function Show(s As String) As Integer Console.WriteLine(s) Return 1 End Function End Module ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( source, TestOptions.DebugExe) compilation.VerifyPdb("Module1.Main", <symbols> <files> <file id="1" name="" language="VB"/> </files> <entryPoint declaringType="Module1" methodName="Main"/> <methods> <method containingType="Module1" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="1" offset="0"/> <slot kind="0" offset="33"/> <slot kind="1" offset="118"/> <slot kind="0" offset="172"/> <slot kind="1" offset="245"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="5" startColumn="5" endLine="5" endColumn="15" document="1"/> <entry offset="0x1" startLine="8" startColumn="9" endLine="8" endColumn="24" document="1"/> <entry offset="0x5" startLine="11" startColumn="9" endLine="11" endColumn="15" document="1"/> <entry offset="0x6" startLine="14" startColumn="9" endLine="14" endColumn="24" document="1"/> <entry offset="0xa" hidden="true" document="1"/> <entry offset="0xb" startLine="16" startColumn="9" endLine="16" endColumn="12" document="1"/> <entry offset="0xe" hidden="true" document="1"/> <entry offset="0x15" startLine="17" startColumn="9" endLine="17" endColumn="30" document="1"/> <entry offset="0x1d" hidden="true" document="1"/> <entry offset="0x1f" startLine="18" startColumn="9" endLine="18" endColumn="16" document="1"/> <entry offset="0x20" startLine="20" startColumn="13" endLine="20" endColumn="28" document="1"/> <entry offset="0x25" hidden="true" document="1"/> <entry offset="0x26" startLine="21" startColumn="9" endLine="21" endColumn="16" document="1"/> <entry offset="0x27" startLine="23" startColumn="5" endLine="23" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x28"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> <scope startOffset="0xe" endOffset="0x1c"> <local name="ex" il_index="3" il_start="0xe" il_end="0x1c" attributes="0"/> </scope> </scope> </method> </methods> </symbols>) End Sub <WorkItem(538944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538944")> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub MissingEndWhileSequencePoint() Dim source = <compilation> <file><![CDATA[ Imports System Module MyMod Sub Main(args As String()) Dim x, y, z As ULong, a, b, c As SByte x = 10 y = 20 z = 30 a = 1 b = 2 c = 3 Dim ct As Integer = 100 Do Console.WriteLine("Out={0}", y) y = y + 2 While (x > a) Do While ct - 50 > a + b * 10 b = b + 1 Console.Write("b={0} | ", b) Do Until z <= ct / 4 Console.Write("z={0} | ", z) Do Console.Write("c={0} | ", c) c = c * 2 Loop Until c > ct / 10 z = z - 4 Loop Loop x = x - 5 Console.WriteLine("x={0}", x) End While Loop While (y < 25) End Sub End Module ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( source, TestOptions.DebugExe) ' startLine="33" compilation.VerifyPdb("MyMod.Main", <symbols> <files> <file id="1" name="" language="VB"/> </files> <entryPoint declaringType="MyMod" methodName="Main" parameterNames="args"/> <methods> <method containingType="MyMod" name="Main" parameterNames="args"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> <slot kind="0" offset="7"/> <slot kind="0" offset="10"/> <slot kind="0" offset="22"/> <slot kind="0" offset="25"/> <slot kind="0" offset="28"/> <slot kind="0" offset="145"/> <slot kind="1" offset="521"/> <slot kind="1" offset="421"/> <slot kind="1" offset="289"/> <slot kind="1" offset="258"/> <slot kind="1" offset="174"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="6" startColumn="5" endLine="6" endColumn="31" document="1"/> <entry offset="0x1" startLine="8" startColumn="9" endLine="8" endColumn="15" document="1"/> <entry offset="0x5" startLine="9" startColumn="9" endLine="9" endColumn="15" document="1"/> <entry offset="0x9" startLine="10" startColumn="9" endLine="10" endColumn="15" document="1"/> <entry offset="0xd" startLine="11" startColumn="9" endLine="11" endColumn="14" document="1"/> <entry offset="0xf" startLine="12" startColumn="9" endLine="12" endColumn="14" document="1"/> <entry offset="0x12" startLine="13" startColumn="9" endLine="13" endColumn="14" document="1"/> <entry offset="0x15" startLine="14" startColumn="13" endLine="14" endColumn="32" document="1"/> <entry offset="0x19" startLine="15" startColumn="9" endLine="15" endColumn="11" document="1"/> <entry offset="0x1a" startLine="16" startColumn="13" endLine="16" endColumn="44" document="1"/> <entry offset="0x2b" startLine="17" startColumn="13" endLine="17" endColumn="22" document="1"/> <entry offset="0x43" hidden="true" document="1"/> <entry offset="0x48" hidden="true" document="1"/> <entry offset="0x4d" startLine="20" startColumn="21" endLine="20" endColumn="30" document="1"/> <entry offset="0x54" startLine="21" startColumn="21" endLine="21" endColumn="49" document="1"/> <entry offset="0x66" hidden="true" document="1"/> <entry offset="0x68" startLine="23" startColumn="25" endLine="23" endColumn="53" document="1"/> <entry offset="0x79" startLine="24" startColumn="25" endLine="24" endColumn="27" document="1"/> <entry offset="0x7a" startLine="25" startColumn="29" endLine="25" endColumn="57" document="1"/> <entry offset="0x8c" startLine="26" startColumn="29" endLine="26" endColumn="38" document="1"/> <entry offset="0x93" startLine="27" startColumn="25" endLine="27" endColumn="47" document="1"/> <entry offset="0xa8" hidden="true" document="1"/> <entry offset="0xac" startLine="28" startColumn="25" endLine="28" endColumn="34" document="1"/> <entry offset="0xc4" startLine="29" startColumn="21" endLine="29" endColumn="25" document="1"/> <entry offset="0xc5" startLine="22" startColumn="21" endLine="22" endColumn="41" document="1"/> <entry offset="0xdc" hidden="true" document="1"/> <entry offset="0xe0" startLine="30" startColumn="17" endLine="30" endColumn="21" document="1"/> <entry offset="0xe1" startLine="19" startColumn="17" endLine="19" endColumn="46" document="1"/> <entry offset="0xf1" hidden="true" document="1"/> <entry offset="0xf8" startLine="31" startColumn="17" endLine="31" endColumn="26" document="1"/> <entry offset="0x110" startLine="32" startColumn="17" endLine="32" endColumn="46" document="1"/> <entry offset="0x121" startLine="33" startColumn="13" endLine="33" endColumn="22" document="1"/> <entry offset="0x122" startLine="18" startColumn="13" endLine="18" endColumn="26" document="1"/> <entry offset="0x138" hidden="true" document="1"/> <entry offset="0x13f" startLine="34" startColumn="9" endLine="34" endColumn="28" document="1"/> <entry offset="0x158" hidden="true" document="1"/> <entry offset="0x15f" startLine="35" startColumn="5" endLine="35" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x160"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> <local name="x" il_index="0" il_start="0x0" il_end="0x160" attributes="0"/> <local name="y" il_index="1" il_start="0x0" il_end="0x160" attributes="0"/> <local name="z" il_index="2" il_start="0x0" il_end="0x160" attributes="0"/> <local name="a" il_index="3" il_start="0x0" il_end="0x160" attributes="0"/> <local name="b" il_index="4" il_start="0x0" il_end="0x160" attributes="0"/> <local name="c" il_index="5" il_start="0x0" il_end="0x160" attributes="0"/> <local name="ct" il_index="6" il_start="0x0" il_end="0x160" attributes="0"/> </scope> </method> </methods> </symbols>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub TestImplicitLocals() Dim source = <compilation> <file> Option Explicit Off Option Strict On Imports System Module Module1 Sub Main() x = "Hello" dim y as string = "world" i% = 3 While i &gt; 0 Console.WriteLine("{0}, {1}", x, y) Console.WriteLine(i) q$ = "string" i = i% - 1 End While End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( source, TestOptions.DebugExe) compilation.VerifyPdb("Module1.Main", <symbols> <files> <file id="1" name="" language="VB"/> </files> <entryPoint declaringType="Module1" methodName="Main"/> <methods> <method containingType="Module1" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="0"/> <slot kind="0" offset="56"/> <slot kind="0" offset="180"/> <slot kind="0" offset="25"/> <slot kind="1" offset="72"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="6" startColumn="5" endLine="6" endColumn="15" document="1"/> <entry offset="0x1" startLine="7" startColumn="9" endLine="7" endColumn="20" document="1"/> <entry offset="0x7" startLine="8" startColumn="13" endLine="8" endColumn="34" document="1"/> <entry offset="0xd" startLine="9" startColumn="9" endLine="9" endColumn="15" document="1"/> <entry offset="0xf" hidden="true" document="1"/> <entry offset="0x11" startLine="11" startColumn="13" endLine="11" endColumn="48" document="1"/> <entry offset="0x23" startLine="12" startColumn="13" endLine="12" endColumn="33" document="1"/> <entry offset="0x2a" startLine="13" startColumn="13" endLine="13" endColumn="26" document="1"/> <entry offset="0x30" startLine="14" startColumn="13" endLine="14" endColumn="23" document="1"/> <entry offset="0x34" startLine="15" startColumn="9" endLine="15" endColumn="18" document="1"/> <entry offset="0x35" startLine="10" startColumn="9" endLine="10" endColumn="20" document="1"/> <entry offset="0x3b" hidden="true" document="1"/> <entry offset="0x3f" startLine="16" startColumn="5" endLine="16" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x40"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> <local name="x" il_index="0" il_start="0x0" il_end="0x40" attributes="0"/> <local name="i" il_index="1" il_start="0x0" il_end="0x40" attributes="0"/> <local name="q" il_index="2" il_start="0x0" il_end="0x40" attributes="0"/> <local name="y" il_index="3" il_start="0x0" il_end="0x40" attributes="0"/> </scope> </method> </methods> </symbols>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub AddRemoveHandler() Dim source = <compilation> <file><![CDATA[ Imports System Module Module1 Sub Main(args As String()) Dim del As System.EventHandler = Sub(sender As Object, a As EventArgs) Console.Write("unload") Dim v = AppDomain.CreateDomain("qq") AddHandler (v.DomainUnload), del RemoveHandler (v.DomainUnload), del AppDomain.Unload(v) End Sub End Module ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( source, TestOptions.DebugExe) compilation.VerifyPdb("Module1.Main", <symbols> <files> <file id="1" name="" language="VB"/> </files> <entryPoint declaringType="Module1" methodName="Main" parameterNames="args"/> <methods> <method containingType="Module1" name="Main" parameterNames="args"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> <slot kind="0" offset="123"/> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>0</methodOrdinal> <lambda offset="46"/> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="4" startColumn="5" endLine="4" endColumn="31" document="1"/> <entry offset="0x1" startLine="5" startColumn="13" endLine="6" endColumn="74" document="1"/> <entry offset="0x26" startLine="8" startColumn="13" endLine="8" endColumn="45" document="1"/> <entry offset="0x31" startLine="10" startColumn="9" endLine="10" endColumn="41" document="1"/> <entry offset="0x39" startLine="11" startColumn="9" endLine="11" endColumn="44" document="1"/> <entry offset="0x41" startLine="13" startColumn="9" endLine="13" endColumn="28" document="1"/> <entry offset="0x48" startLine="14" startColumn="5" endLine="14" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x49"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> <local name="del" il_index="0" il_start="0x0" il_end="0x49" attributes="0"/> <local name="v" il_index="1" il_start="0x0" il_end="0x49" attributes="0"/> </scope> </method> </methods> </symbols>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub SelectCase_NoCaseBlocks() Dim source = <compilation> <file><![CDATA[ Imports System Module Module1 Sub Main() Dim num As Integer = 0 Select Case num End Select End Sub End Module ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe) compilation.VerifyPdb("Module1.Main", <symbols> <files> <file id="1" name="" language="VB"/> </files> <entryPoint declaringType="Module1" methodName="Main"/> <methods> <method containingType="Module1" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="3" startColumn="5" endLine="3" endColumn="15" document="1"/> <entry offset="0x1" startLine="4" startColumn="13" endLine="4" endColumn="31" document="1"/> <entry offset="0x3" startLine="5" startColumn="9" endLine="5" endColumn="24" document="1"/> <entry offset="0x4" startLine="6" startColumn="9" endLine="6" endColumn="19" document="1"/> <entry offset="0x5" startLine="7" startColumn="5" endLine="7" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x6"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> <local name="num" il_index="0" il_start="0x0" il_end="0x6" attributes="0"/> </scope> </method> </methods> </symbols>) CompileAndVerify(compilation, expectedOutput:="") End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub SelectCase_SingleCaseStatement() Dim source = <compilation> <file><![CDATA[ Imports System Module Module1 Sub Main() Dim num As Integer = 0 Select Case num Case 1 End Select Select Case num Case Else End Select End Sub End Module ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe) compilation.VerifyPdb("Module1.Main", <symbols> <files> <file id="1" name="" language="VB"/> </files> <entryPoint declaringType="Module1" methodName="Main"/> <methods> <method containingType="Module1" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="3" startColumn="5" endLine="3" endColumn="15" document="1"/> <entry offset="0x1" startLine="4" startColumn="13" endLine="4" endColumn="31" document="1"/> <entry offset="0x3" startLine="5" startColumn="9" endLine="5" endColumn="24" document="1"/> <entry offset="0xa" startLine="6" startColumn="13" endLine="6" endColumn="19" document="1"/> <entry offset="0xd" startLine="7" startColumn="9" endLine="7" endColumn="19" document="1"/> <entry offset="0xe" startLine="9" startColumn="9" endLine="9" endColumn="24" document="1"/> <entry offset="0x11" startLine="10" startColumn="13" endLine="10" endColumn="22" document="1"/> <entry offset="0x14" startLine="11" startColumn="9" endLine="11" endColumn="19" document="1"/> <entry offset="0x15" startLine="12" startColumn="5" endLine="12" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x16"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> <local name="num" il_index="0" il_start="0x0" il_end="0x16" attributes="0"/> </scope> </method> </methods> </symbols>) CompileAndVerify(compilation, expectedOutput:="") End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub SelectCase_OnlyCaseStatements() Dim source = <compilation> <file><![CDATA[ Imports System Module Module1 Sub Main() Dim num As Integer = 0 Select Case num Case 1 Case 2 Case 0, 3 To 8 Case Else End Select End Sub End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe) CompileAndVerify(compilation).VerifyIL("Module1.Main", " { // Code size 55 (0x37) .maxstack 2 .locals init (Integer V_0, //num Integer V_1, Boolean V_2) -IL_0000: nop -IL_0001: ldc.i4.0 IL_0002: stloc.0 -IL_0003: nop IL_0004: ldloc.0 IL_0005: stloc.1 -IL_0006: ldloc.1 IL_0007: ldc.i4.1 IL_0008: ceq IL_000a: stloc.2 ~IL_000b: ldloc.2 IL_000c: brfalse.s IL_0010 IL_000e: br.s IL_0035 -IL_0010: ldloc.1 IL_0011: ldc.i4.2 IL_0012: ceq IL_0014: stloc.2 ~IL_0015: ldloc.2 IL_0016: brfalse.s IL_001a IL_0018: br.s IL_0035 -IL_001a: ldloc.1 IL_001b: brfalse.s IL_002d IL_001d: ldloc.1 IL_001e: ldc.i4.3 IL_001f: blt.s IL_002a IL_0021: ldloc.1 IL_0022: ldc.i4.8 IL_0023: cgt IL_0025: ldc.i4.0 IL_0026: ceq IL_0028: br.s IL_002b IL_002a: ldc.i4.0 IL_002b: br.s IL_002e IL_002d: ldc.i4.1 IL_002e: stloc.2 ~IL_002f: ldloc.2 IL_0030: brfalse.s IL_0034 IL_0032: br.s IL_0035 -IL_0034: nop -IL_0035: nop -IL_0036: ret } ", sequencePoints:="Module1.Main") compilation.VerifyPdb("Module1.Main", <symbols> <files> <file id="1" name="" language="VB"/> </files> <entryPoint declaringType="Module1" methodName="Main"/> <methods> <method containingType="Module1" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> <slot kind="15" offset="32"/> <slot kind="1" offset="32"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="3" startColumn="5" endLine="3" endColumn="15" document="1"/> <entry offset="0x1" startLine="4" startColumn="13" endLine="4" endColumn="31" document="1"/> <entry offset="0x3" startLine="5" startColumn="9" endLine="5" endColumn="24" document="1"/> <entry offset="0x6" startLine="6" startColumn="13" endLine="6" endColumn="19" document="1"/> <entry offset="0xb" hidden="true" document="1"/> <entry offset="0x10" startLine="7" startColumn="13" endLine="7" endColumn="19" document="1"/> <entry offset="0x15" hidden="true" document="1"/> <entry offset="0x1a" startLine="8" startColumn="13" endLine="8" endColumn="27" document="1"/> <entry offset="0x2f" hidden="true" document="1"/> <entry offset="0x34" startLine="9" startColumn="13" endLine="9" endColumn="22" document="1"/> <entry offset="0x35" startLine="10" startColumn="9" endLine="10" endColumn="19" document="1"/> <entry offset="0x36" startLine="11" startColumn="5" endLine="11" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x37"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> <local name="num" il_index="0" il_start="0x0" il_end="0x37" attributes="0"/> </scope> </method> </methods> </symbols>) CompileAndVerify(compilation, expectedOutput:="") End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub SelectCase_SwitchTable() Dim source = <compilation> <file><![CDATA[ Imports System Module Module1 Sub Main() Dim num As Integer = 0 Select Case num Case 1 Console.WriteLine("1") Case 2 Console.WriteLine("2") Case 0, 3, 4, 5, 6, Is = 7, 8 Case Else Console.WriteLine("Else") End Select End Sub End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe) compilation.VerifyPdb("Module1.Main", <symbols> <files> <file id="1" name="" language="VB"/> </files> <entryPoint declaringType="Module1" methodName="Main"/> <methods> <method containingType="Module1" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="3" startColumn="5" endLine="3" endColumn="15" document="1"/> <entry offset="0x1" startLine="4" startColumn="13" endLine="4" endColumn="31" document="1"/> <entry offset="0x3" startLine="5" startColumn="9" endLine="5" endColumn="24" document="1"/> <entry offset="0x30" startLine="6" startColumn="13" endLine="6" endColumn="19" document="1"/> <entry offset="0x31" startLine="7" startColumn="17" endLine="7" endColumn="39" document="1"/> <entry offset="0x3e" startLine="8" startColumn="13" endLine="8" endColumn="19" document="1"/> <entry offset="0x3f" startLine="9" startColumn="17" endLine="9" endColumn="39" document="1"/> <entry offset="0x4c" startLine="10" startColumn="13" endLine="10" endColumn="42" document="1"/> <entry offset="0x4f" startLine="11" startColumn="13" endLine="11" endColumn="22" document="1"/> <entry offset="0x50" startLine="12" startColumn="17" endLine="12" endColumn="42" document="1"/> <entry offset="0x5d" startLine="13" startColumn="9" endLine="13" endColumn="19" document="1"/> <entry offset="0x5e" startLine="14" startColumn="5" endLine="14" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x5f"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> <local name="num" il_index="0" il_start="0x0" il_end="0x5f" attributes="0"/> </scope> </method> </methods> </symbols>) CompileAndVerify(compilation, expectedOutput:="") End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub SelectCase_SwitchTable_TempUsed() Dim source = <compilation> <file><![CDATA[ Imports System Module Module1 Sub Main() Dim num As Integer = 0 Select Case num + 1 Case 1 Console.WriteLine("") Case 2 Console.WriteLine("2") Case 0, 3, 4, 5, 6, Is = 7, 8 Console.WriteLine("0") Case Else Console.WriteLine("Else") End Select End Sub End Module ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe) compilation.VerifyPdb("Module1.Main", <symbols> <files> <file id="1" name="" language="VB"/> </files> <entryPoint declaringType="Module1" methodName="Main"/> <methods> <method containingType="Module1" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> <slot kind="15" offset="32"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="3" startColumn="5" endLine="3" endColumn="15" document="1"/> <entry offset="0x1" startLine="4" startColumn="13" endLine="4" endColumn="31" document="1"/> <entry offset="0x3" startLine="5" startColumn="9" endLine="5" endColumn="28" document="1"/> <entry offset="0x34" startLine="6" startColumn="13" endLine="6" endColumn="19" document="1"/> <entry offset="0x35" startLine="7" startColumn="17" endLine="7" endColumn="38" document="1"/> <entry offset="0x42" startLine="8" startColumn="13" endLine="8" endColumn="19" document="1"/> <entry offset="0x43" startLine="9" startColumn="17" endLine="9" endColumn="39" document="1"/> <entry offset="0x50" startLine="10" startColumn="13" endLine="10" endColumn="42" document="1"/> <entry offset="0x51" startLine="11" startColumn="17" endLine="11" endColumn="39" document="1"/> <entry offset="0x5e" startLine="12" startColumn="13" endLine="12" endColumn="22" document="1"/> <entry offset="0x5f" startLine="13" startColumn="17" endLine="13" endColumn="42" document="1"/> <entry offset="0x6c" startLine="14" startColumn="9" endLine="14" endColumn="19" document="1"/> <entry offset="0x6d" startLine="15" startColumn="5" endLine="15" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x6e"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> <local name="num" il_index="0" il_start="0x0" il_end="0x6e" attributes="0"/> </scope> </method> </methods> </symbols>) CompileAndVerify(compilation, expectedOutput:="") End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub SelectCase_IfList() Dim source = <compilation> <file><![CDATA[ Imports System Module Module1 Sub Main() Dim num As Integer = 0 Select Case num Case 1 Console.WriteLine("1") Case 2 Console.WriteLine("2") Case 0, >= 3, <= 8 Case Else Console.WriteLine("Else") End Select End Sub End Module ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe) compilation.VerifyPdb("Module1.Main", <symbols> <files> <file id="1" name="" language="VB"/> </files> <entryPoint declaringType="Module1" methodName="Main"/> <methods> <method containingType="Module1" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> <slot kind="15" offset="32"/> <slot kind="1" offset="32"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="3" startColumn="5" endLine="3" endColumn="15" document="1"/> <entry offset="0x1" startLine="4" startColumn="13" endLine="4" endColumn="31" document="1"/> <entry offset="0x3" startLine="5" startColumn="9" endLine="5" endColumn="24" document="1"/> <entry offset="0x6" startLine="6" startColumn="13" endLine="6" endColumn="19" document="1"/> <entry offset="0xb" hidden="true" document="1"/> <entry offset="0xe" startLine="7" startColumn="17" endLine="7" endColumn="39" document="1"/> <entry offset="0x1b" startLine="8" startColumn="13" endLine="8" endColumn="19" document="1"/> <entry offset="0x20" hidden="true" document="1"/> <entry offset="0x23" startLine="9" startColumn="17" endLine="9" endColumn="39" document="1"/> <entry offset="0x30" startLine="10" startColumn="13" endLine="10" endColumn="31" document="1"/> <entry offset="0x42" hidden="true" document="1"/> <entry offset="0x47" startLine="12" startColumn="17" endLine="12" endColumn="42" document="1"/> <entry offset="0x52" startLine="13" startColumn="9" endLine="13" endColumn="19" document="1"/> <entry offset="0x53" startLine="14" startColumn="5" endLine="14" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x54"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> <local name="num" il_index="0" il_start="0x0" il_end="0x54" attributes="0"/> </scope> </method> </methods> </symbols>) CompileAndVerify(compilation, expectedOutput:="") End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub SelectCase_IfList_TempUsed() Dim source = <compilation> <file><![CDATA[ Imports System Module Module1 Sub Main() Dim num As Integer = 0 Select Case num + 1 Case 1 Console.WriteLine("") Case 2 Console.WriteLine("2") Case 0, >= 3, <= 8 Console.WriteLine("0") Case Else Console.WriteLine("Else") End Select End Sub End Module ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe) compilation.VerifyPdb("Module1.Main", <symbols> <files> <file id="1" name="" language="VB"/> </files> <entryPoint declaringType="Module1" methodName="Main"/> <methods> <method containingType="Module1" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> <slot kind="15" offset="32"/> <slot kind="1" offset="32"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="3" startColumn="5" endLine="3" endColumn="15" document="1"/> <entry offset="0x1" startLine="4" startColumn="13" endLine="4" endColumn="31" document="1"/> <entry offset="0x3" startLine="5" startColumn="9" endLine="5" endColumn="28" document="1"/> <entry offset="0x8" startLine="6" startColumn="13" endLine="6" endColumn="19" document="1"/> <entry offset="0xd" hidden="true" document="1"/> <entry offset="0x10" startLine="7" startColumn="17" endLine="7" endColumn="38" document="1"/> <entry offset="0x1d" startLine="8" startColumn="13" endLine="8" endColumn="19" document="1"/> <entry offset="0x22" hidden="true" document="1"/> <entry offset="0x25" startLine="9" startColumn="17" endLine="9" endColumn="39" document="1"/> <entry offset="0x32" startLine="10" startColumn="13" endLine="10" endColumn="31" document="1"/> <entry offset="0x44" hidden="true" document="1"/> <entry offset="0x47" startLine="11" startColumn="17" endLine="11" endColumn="39" document="1"/> <entry offset="0x54" startLine="13" startColumn="17" endLine="13" endColumn="42" document="1"/> <entry offset="0x5f" startLine="14" startColumn="9" endLine="14" endColumn="19" document="1"/> <entry offset="0x60" startLine="15" startColumn="5" endLine="15" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x61"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> <local name="num" il_index="0" il_start="0x0" il_end="0x61" attributes="0"/> </scope> </method> </methods> </symbols>) CompileAndVerify(compilation, expectedOutput:="") End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub SelectCase_String_SwitchTable_Hash() Dim source = <compilation> <file><![CDATA[ Imports System Module Module1 Sub Main() Dim str As String = "00" Select Case str Case "01" Console.WriteLine("01") Case "02" Console.WriteLine("02") Case "00", "03", "04", "05", "06", "07", "08" Case Else Console.WriteLine("Else") End Select End Sub End Module ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe) compilation.VerifyPdb("Module1.Main", <symbols> <files> <file id="1" name="" language="VB"/> </files> <entryPoint declaringType="Module1" methodName="Main"/> <methods> <method containingType="Module1" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> <slot kind="temp"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="3" startColumn="5" endLine="3" endColumn="15" document="1"/> <entry offset="0x1" startLine="4" startColumn="13" endLine="4" endColumn="33" document="1"/> <entry offset="0x7" startLine="5" startColumn="9" endLine="5" endColumn="24" document="1"/> <entry offset="0x135" startLine="6" startColumn="13" endLine="6" endColumn="22" document="1"/> <entry offset="0x136" startLine="7" startColumn="17" endLine="7" endColumn="40" document="1"/> <entry offset="0x143" startLine="8" startColumn="13" endLine="8" endColumn="22" document="1"/> <entry offset="0x144" startLine="9" startColumn="17" endLine="9" endColumn="40" document="1"/> <entry offset="0x151" startLine="10" startColumn="13" endLine="10" endColumn="58" document="1"/> <entry offset="0x154" startLine="11" startColumn="13" endLine="11" endColumn="22" document="1"/> <entry offset="0x155" startLine="12" startColumn="17" endLine="12" endColumn="42" document="1"/> <entry offset="0x162" startLine="13" startColumn="9" endLine="13" endColumn="19" document="1"/> <entry offset="0x163" startLine="14" startColumn="5" endLine="14" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x164"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> <local name="str" il_index="0" il_start="0x0" il_end="0x164" attributes="0"/> </scope> </method> </methods> </symbols>) CompileAndVerify(compilation, expectedOutput:="") End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub SelectCase_String_SwitchTable_NonHash() Dim source = <compilation> <file><![CDATA[ Imports System Module Module1 Sub Main() Dim str As String = "00" Select Case str Case "01" Console.WriteLine("01") Case "02" Case "00" Console.WriteLine("00") Case Else End Select End Sub End Module ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe) compilation.VerifyPdb("Module1.Main", <symbols> <files> <file id="1" name="" language="VB"/> </files> <entryPoint declaringType="Module1" methodName="Main"/> <methods> <method containingType="Module1" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="3" startColumn="5" endLine="3" endColumn="15" document="1"/> <entry offset="0x1" startLine="4" startColumn="13" endLine="4" endColumn="33" document="1"/> <entry offset="0x7" startLine="5" startColumn="9" endLine="5" endColumn="24" document="1"/> <entry offset="0x34" startLine="6" startColumn="13" endLine="6" endColumn="22" document="1"/> <entry offset="0x35" startLine="7" startColumn="17" endLine="7" endColumn="40" document="1"/> <entry offset="0x42" startLine="8" startColumn="13" endLine="8" endColumn="22" document="1"/> <entry offset="0x45" startLine="9" startColumn="13" endLine="9" endColumn="22" document="1"/> <entry offset="0x46" startLine="10" startColumn="17" endLine="10" endColumn="40" document="1"/> <entry offset="0x53" startLine="11" startColumn="13" endLine="11" endColumn="22" document="1"/> <entry offset="0x56" startLine="12" startColumn="9" endLine="12" endColumn="19" document="1"/> <entry offset="0x57" startLine="13" startColumn="5" endLine="13" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x58"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> <local name="str" il_index="0" il_start="0x0" il_end="0x58" attributes="0"/> </scope> </method> </methods> </symbols>) CompileAndVerify(compilation, expectedOutput:="00") End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub SelectCase_String_IfList() Dim source = <compilation> <file><![CDATA[ Imports System Module Module1 Sub Main() Dim str As String = "00" Select Case str Case "01" Console.WriteLine("01") Case "02", 3.ToString() Case "00" Console.WriteLine("00") End Select End Sub End Module ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe) compilation.VerifyPdb("Module1.Main", <symbols> <files> <file id="1" name="" language="VB"/> </files> <entryPoint declaringType="Module1" methodName="Main"/> <methods> <method containingType="Module1" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> <slot kind="15" offset="34"/> <slot kind="1" offset="34"/> <slot kind="temp"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="3" startColumn="5" endLine="3" endColumn="15" document="1"/> <entry offset="0x1" startLine="4" startColumn="13" endLine="4" endColumn="33" document="1"/> <entry offset="0x7" startLine="5" startColumn="9" endLine="5" endColumn="24" document="1"/> <entry offset="0xa" startLine="6" startColumn="13" endLine="6" endColumn="22" document="1"/> <entry offset="0x1a" hidden="true" document="1"/> <entry offset="0x1d" startLine="7" startColumn="17" endLine="7" endColumn="40" document="1"/> <entry offset="0x2a" startLine="8" startColumn="13" endLine="8" endColumn="36" document="1"/> <entry offset="0x4f" hidden="true" document="1"/> <entry offset="0x54" startLine="9" startColumn="13" endLine="9" endColumn="22" document="1"/> <entry offset="0x64" hidden="true" document="1"/> <entry offset="0x67" startLine="10" startColumn="17" endLine="10" endColumn="40" document="1"/> <entry offset="0x72" startLine="11" startColumn="9" endLine="11" endColumn="19" document="1"/> <entry offset="0x73" startLine="12" startColumn="5" endLine="12" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x74"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> <local name="str" il_index="0" il_start="0x0" il_end="0x74" attributes="0"/> </scope> </method> </methods> </symbols>) CompileAndVerify(compilation, expectedOutput:="00") End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub DontEmit_AnonymousType_NoKeys() Dim source = <compilation> <file><![CDATA[ Class C1 Sub Method() Dim o = New With { .a = 1 } End Sub End Class ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugDll) compilation.VerifyPdb( <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="C1" name="Method"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="2" startColumn="5" endLine="2" endColumn="17" document="1"/> <entry offset="0x1" startLine="3" startColumn="13" endLine="3" endColumn="36" document="1"/> <entry offset="0x8" startLine="4" startColumn="5" endLine="4" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x9"> <currentnamespace name=""/> <local name="o" il_index="0" il_start="0x0" il_end="0x9" attributes="0"/> </scope> </method> </methods> </symbols>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub DontEmit_AnonymousType_WithKeys() Dim source = <compilation> <file><![CDATA[ Class C1 Sub Method() Dim o = New With { Key .a = 1 } End Sub End Class ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugDll) compilation.VerifyPdb( <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="C1" name="Method"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="2" startColumn="5" endLine="2" endColumn="17" document="1"/> <entry offset="0x1" startLine="3" startColumn="13" endLine="3" endColumn="40" document="1"/> <entry offset="0x8" startLine="4" startColumn="5" endLine="4" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x9"> <currentnamespace name=""/> <local name="o" il_index="0" il_start="0x0" il_end="0x9" attributes="0"/> </scope> </method> </methods> </symbols>) End Sub <WorkItem(727419, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/727419")> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub Bug727419() Dim source = <compilation> <file><![CDATA[ Option Strict Off Option Explicit Off Imports System Class GooDerived Public Sub ComputeMatrix(ByVal rank As Integer) Dim I As Integer Dim J As Long Dim q() As Long Dim count As Long Dim dims() As Long ' allocate space for arrays ReDim q(rank) ReDim dims(rank) ' create the dimensions count = 1 For I = 0 To rank - 1 q(I) = 0 dims(I) = CLng(2 ^ I) count *= dims(I) Next I End Sub End Class Module Variety Sub Main() Dim a As New GooDerived() a.ComputeMatrix(2) End Sub End Module ' End of File ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( source, TestOptions.DebugExe) compilation.VerifyPdb("GooDerived.ComputeMatrix", <symbols> <files> <file id="1" name="" language="VB"/> </files> <entryPoint declaringType="Variety" methodName="Main"/> <methods> <method containingType="GooDerived" name="ComputeMatrix" parameterNames="rank"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> <slot kind="0" offset="30"/> <slot kind="0" offset="53"/> <slot kind="0" offset="78"/> <slot kind="0" offset="105"/> <slot kind="11" offset="271"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="6" startColumn="5" endLine="6" endColumn="52" document="1"/> <entry offset="0x1" startLine="14" startColumn="15" endLine="14" endColumn="22" document="1"/> <entry offset="0xa" startLine="15" startColumn="15" endLine="15" endColumn="25" document="1"/> <entry offset="0x14" startLine="18" startColumn="9" endLine="18" endColumn="18" document="1"/> <entry offset="0x17" startLine="19" startColumn="9" endLine="19" endColumn="30" document="1"/> <entry offset="0x1e" hidden="true" document="1"/> <entry offset="0x20" startLine="20" startColumn="13" endLine="20" endColumn="21" document="1"/> <entry offset="0x25" startLine="21" startColumn="13" endLine="21" endColumn="34" document="1"/> <entry offset="0x3f" startLine="22" startColumn="13" endLine="22" endColumn="29" document="1"/> <entry offset="0x46" startLine="23" startColumn="9" endLine="23" endColumn="15" document="1"/> <entry offset="0x4a" hidden="true" document="1"/> <entry offset="0x4f" startLine="24" startColumn="5" endLine="24" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x50"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> <local name="I" il_index="0" il_start="0x0" il_end="0x50" attributes="0"/> <local name="J" il_index="1" il_start="0x0" il_end="0x50" attributes="0"/> <local name="q" il_index="2" il_start="0x0" il_end="0x50" attributes="0"/> <local name="count" il_index="3" il_start="0x0" il_end="0x50" attributes="0"/> <local name="dims" il_index="4" il_start="0x0" il_end="0x50" attributes="0"/> </scope> </method> </methods> </symbols>) End Sub <WorkItem(722627, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/722627")> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub Bug722627() Dim source = <compilation> <file><![CDATA[ Imports System Friend Module SubMod Sub Main() L0: GoTo L2 L1: Exit Sub L2: GoTo L1 End Sub End Module ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( source, TestOptions.DebugExe) compilation.VerifyPdb("SubMod.Main", <symbols> <files> <file id="1" name="" language="VB"/> </files> <entryPoint declaringType="SubMod" methodName="Main"/> <methods> <method containingType="SubMod" name="Main"> <sequencePoints> <entry offset="0x0" startLine="3" startColumn="5" endLine="3" endColumn="15" document="1"/> <entry offset="0x1" startLine="4" startColumn="1" endLine="4" endColumn="4" document="1"/> <entry offset="0x2" startLine="5" startColumn="9" endLine="5" endColumn="16" document="1"/> <entry offset="0x4" startLine="6" startColumn="1" endLine="6" endColumn="4" document="1"/> <entry offset="0x5" startLine="7" startColumn="9" endLine="7" endColumn="17" document="1"/> <entry offset="0x7" startLine="8" startColumn="1" endLine="8" endColumn="4" document="1"/> <entry offset="0x8" startLine="9" startColumn="9" endLine="9" endColumn="16" document="1"/> <entry offset="0xa" startLine="10" startColumn="5" endLine="10" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0xb"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> </scope> </method> </methods> </symbols>) End Sub <WorkItem(543703, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543703")> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub DontIncludeMethodAttributesInSeqPoint() Dim source = <compilation> <file><![CDATA[ Imports System Module M1 Sub Main() S() End Sub <System.Runtime.InteropServices.PreserveSigAttribute()> <CLSCompliantAttribute(False)> Public Sub S() End Sub End Module ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugDll) compilation.VerifyPdb( <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="M1" name="Main"> <sequencePoints> <entry offset="0x0" startLine="3" startColumn="5" endLine="3" endColumn="15" document="1"/> <entry offset="0x1" startLine="4" startColumn="9" endLine="4" endColumn="12" document="1"/> <entry offset="0x7" startLine="5" startColumn="5" endLine="5" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x8"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> </scope> </method> <method containingType="M1" name="S"> <sequencePoints> <entry offset="0x0" startLine="9" startColumn="5" endLine="9" endColumn="19" document="1"/> <entry offset="0x1" startLine="11" startColumn="5" endLine="11" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x2"> <importsforward declaringType="M1" methodName="Main"/> </scope> </method> </methods> </symbols>) End Sub <WorkItem(529300, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529300")> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub DontShowOperatorNameCTypeInLocals() Dim source = <compilation> <file><![CDATA[ Imports System Module Module1 Class B2 Public f As Integer Public Sub New(x As Integer) f = x End Sub Shared Widening Operator CType(x As Integer) As B2 Return New B2(x) End Operator End Class Sub Main() Dim x As Integer = 11 Dim b2 As B2 = x End Sub End Module ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugDll) compilation.VerifyPdb( <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="Module1" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> <slot kind="0" offset="35"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="17" startColumn="5" endLine="17" endColumn="15" document="1"/> <entry offset="0x1" startLine="18" startColumn="13" endLine="18" endColumn="30" document="1"/> <entry offset="0x4" startLine="19" startColumn="13" endLine="19" endColumn="25" document="1"/> <entry offset="0xb" startLine="20" startColumn="5" endLine="20" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0xc"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> <local name="x" il_index="0" il_start="0x0" il_end="0xc" attributes="0"/> <local name="b2" il_index="1" il_start="0x0" il_end="0xc" attributes="0"/> </scope> </method> <method containingType="Module1+B2" name=".ctor" parameterNames="x"> <sequencePoints> <entry offset="0x0" startLine="8" startColumn="9" endLine="8" endColumn="37" document="1"/> <entry offset="0x8" startLine="9" startColumn="13" endLine="9" endColumn="18" document="1"/> <entry offset="0xf" startLine="10" startColumn="9" endLine="10" endColumn="16" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x10"> <importsforward declaringType="Module1" methodName="Main"/> </scope> </method> <method containingType="Module1+B2" name="op_Implicit" parameterNames="x"> <customDebugInfo> <encLocalSlotMap> <slot kind="21" offset="-1"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="12" startColumn="9" endLine="12" endColumn="59" document="1"/> <entry offset="0x1" startLine="13" startColumn="13" endLine="13" endColumn="29" document="1"/> <entry offset="0xa" startLine="14" startColumn="9" endLine="14" endColumn="21" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0xc"> <importsforward declaringType="Module1" methodName="Main"/> </scope> </method> </methods> </symbols>) End Sub <WorkItem(760994, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/760994")> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub Bug760994() Dim source = <compilation> <file><![CDATA[ Imports System Class CLAZZ Public FLD1 As Integer = 1 Public Event Load As Action Public FLD2 As Integer = 1 Public Sub New() End Sub Private Sub frmMain_Load() Handles Me.Load End Sub End Class Module Program Sub Main(args As String()) Dim c As New CLAZZ End Sub End Module ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugDll) compilation.VerifyPdb("CLAZZ..ctor", <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="CLAZZ" name=".ctor"> <sequencePoints> <entry offset="0x0" startLine="8" startColumn="5" endLine="8" endColumn="21" document="1"/> <entry offset="0x1b" startLine="4" startColumn="12" endLine="4" endColumn="31" document="1"/> <entry offset="0x22" startLine="6" startColumn="12" endLine="6" endColumn="31" document="1"/> <entry offset="0x29" startLine="10" startColumn="5" endLine="10" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x2a"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> </scope> </method> </methods> </symbols>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub WRN_PDBConstantStringValueTooLong() Dim longStringValue = New String("a"c, 2050) Dim source = <compilation> <file> Imports System Module Module1 Sub Main() Const goo as String = "<%= longStringValue %>" Console.WriteLine("Hello Word.") Console.WriteLine(goo) End Sub End Module </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe) Dim exebits = New IO.MemoryStream() Dim pdbbits = New IO.MemoryStream() Dim result = compilation.Emit(exebits, pdbbits) result.Diagnostics.Verify() 'this new warning was abandoned 'result.Diagnostics.Verify(Diagnostic(ERRID.WRN_PDBConstantStringValueTooLong).WithArguments("goo", longStringValue.Substring(0, 20) & "...")) ''ensure that the warning is suppressable 'compilation = CreateCompilationWithMscorlibAndVBRuntime(source, OptionsExe.WithDebugInformationKind(Common.DebugInformationKind.Full).WithOptimizations(False). ' WithSpecificDiagnosticOptions(New Dictionary(Of Integer, ReportWarning) From {{CInt(ERRID.WRN_PDBConstantStringValueTooLong), ReportWarning.Suppress}})) 'result = compilation.Emit(exebits, Nothing, "DontCare", pdbbits, Nothing) 'result.Diagnostics.Verify() ''ensure that the warning can be turned into an error 'compilation = CreateCompilationWithMscorlibAndVBRuntime(source, OptionsExe.WithDebugInformationKind(Common.DebugInformationKind.Full).WithOptimizations(False). ' WithSpecificDiagnosticOptions(New Dictionary(Of Integer, ReportWarning) From {{CInt(ERRID.WRN_PDBConstantStringValueTooLong), ReportWarning.Error}})) 'result = compilation.Emit(exebits, Nothing, "DontCare", pdbbits, Nothing) 'Assert.False(result.Success) 'result.Diagnostics.Verify(Diagnostic(ERRID.WRN_PDBConstantStringValueTooLong).WithArguments("goo", longStringValue.Substring(0, 20) & "...").WithWarningAsError(True), ' Diagnostic(ERRID.ERR_WarningTreatedAsError).WithArguments("The value assigned to the constant string 'goo' is too long to be used in a PDB file. Consider shortening the value, otherwise the string's value will not be visible in the debugger. Only the debug experience is affected.")) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub NoDebugInfoForEmbeddedSymbols() Dim source = <compilation> <file> Imports Microsoft.VisualBasic.Strings Public Class C Public Shared Function F(z As Integer) As Char Return ChrW(z) End Function End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugDll.WithEmbedVbCoreRuntime(True)) ' Dev11 generates debug info for embedded symbols. There is no reason to do so since the source code is not available to the user. compilation.VerifyPdb( <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="C" name="F" parameterNames="z"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="4" startColumn="5" endLine="4" endColumn="51" document="1"/> <entry offset="0x1" startLine="5" startColumn="9" endLine="5" endColumn="23" document="1"/> <entry offset="0xa" startLine="6" startColumn="5" endLine="6" endColumn="17" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0xc"> <type name="Microsoft.VisualBasic.Strings" importlevel="file"/> <currentnamespace name=""/> <local name="F" il_index="0" il_start="0x0" il_end="0xc" attributes="0"/> </scope> </method> </methods> </symbols>) End Sub <WorkItem(797482, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/797482")> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub Bug797482() Dim source = <compilation> <file><![CDATA[ Imports System Module Module1 Sub Main() Console.WriteLine(MakeIncrementer(5)(2)) End Sub Function MakeIncrementer(n As Integer) As Func(Of Integer, Integer) Return Function(i) Return i + n End Function End Function End Module ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugDll) compilation.VerifyPdb("Module1.MakeIncrementer", <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="Module1" name="MakeIncrementer" parameterNames="n"> <customDebugInfo> <encLocalSlotMap> <slot kind="30" offset="-1"/> <slot kind="0" offset="-1"/> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>1</methodOrdinal> <closure offset="-1"/> <lambda offset="7" closure="0"/> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="7" startColumn="5" endLine="7" endColumn="72" document="1"/> <entry offset="0x1" hidden="true" document="1"/> <entry offset="0xe" startLine="8" startColumn="9" endLine="10" endColumn="21" document="1"/> <entry offset="0x1d" startLine="11" startColumn="5" endLine="11" endColumn="17" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x1f"> <importsforward declaringType="Module1" methodName="Main"/> <local name="$VB$Closure_0" il_index="0" il_start="0x0" il_end="0x1f" attributes="0"/> <local name="MakeIncrementer" il_index="1" il_start="0x0" il_end="0x1f" attributes="0"/> </scope> </method> </methods> </symbols>) End Sub ''' <summary> ''' If a synthesized .ctor contains user code (field initializers), ''' the method must have a sequence point at ''' offset 0 for correct stepping behavior. ''' </summary> <WorkItem(804681, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/804681")> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub DefaultConstructorWithInitializer() Dim source = <compilation> <file><![CDATA[ Class C Private o As Object = New Object() End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) compilation.VerifyPdb("C..ctor", <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="C" name=".ctor"> <sequencePoints> <entry offset="0x0" hidden="true" document="1"/> <entry offset="0x7" startLine="2" startColumn="13" endLine="2" endColumn="39" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x18"> <currentnamespace name=""/> </scope> </method> </methods> </symbols>) End Sub ''' <summary> ''' If a synthesized method contains any user code, ''' the method must have a sequence point at ''' offset 0 for correct stepping behavior. ''' </summary> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub SequencePointAtOffset0() Dim source = <compilation> <file><![CDATA[ Imports System Module M Private Fn As Func(Of Object, Integer) = Function(x) Dim f As Func(Of Object, Integer) = Function(o) 1 Dim g As Func(Of Func(Of Object, Integer), Func(Of Object, Integer)) = Function(h) Function(y) h(y) Return g(f)(Nothing) End Function End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugDll) compilation.VerifyPdb( <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="M" name=".cctor"> <customDebugInfo> <encLambdaMap> <methodOrdinal>0</methodOrdinal> <closure offset="-84"/> <lambda offset="-243"/> <lambda offset="-182"/> <lambda offset="-84"/> <lambda offset="-72" closure="0"/> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="3" startColumn="13" endLine="7" endColumn="21" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x16"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> </scope> </method> <method containingType="M+_Closure$__0-0" name="_Lambda$__3" parameterNames="y"> <customDebugInfo> <encLocalSlotMap> <slot kind="21" offset="-72"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="5" startColumn="96" endLine="5" endColumn="107" document="1"/> <entry offset="0x1" startLine="5" startColumn="108" endLine="5" endColumn="112" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x17"> <importsforward declaringType="M" methodName=".cctor"/> </scope> </method> <method containingType="M+_Closure$__" name="_Lambda$__0-0" parameterNames="x"> <customDebugInfo> <encLocalSlotMap> <slot kind="21" offset="-243"/> <slot kind="0" offset="-214"/> <slot kind="0" offset="-151"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="3" startColumn="46" endLine="3" endColumn="57" document="1"/> <entry offset="0x1" startLine="4" startColumn="17" endLine="4" endColumn="62" document="1"/> <entry offset="0x26" startLine="5" startColumn="17" endLine="5" endColumn="112" document="1"/> <entry offset="0x4b" startLine="6" startColumn="13" endLine="6" endColumn="33" document="1"/> <entry offset="0x5b" startLine="7" startColumn="9" endLine="7" endColumn="21" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x5d"> <importsforward declaringType="M" methodName=".cctor"/> <local name="f" il_index="1" il_start="0x0" il_end="0x5d" attributes="0"/> <local name="g" il_index="2" il_start="0x0" il_end="0x5d" attributes="0"/> </scope> </method> <method containingType="M+_Closure$__" name="_Lambda$__0-1" parameterNames="o"> <customDebugInfo> <encLocalSlotMap> <slot kind="21" offset="-182"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="4" startColumn="49" endLine="4" endColumn="60" document="1"/> <entry offset="0x1" startLine="4" startColumn="61" endLine="4" endColumn="62" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x7"> <importsforward declaringType="M" methodName=".cctor"/> </scope> </method> <method containingType="M+_Closure$__" name="_Lambda$__0-2" parameterNames="h"> <customDebugInfo> <encLocalSlotMap> <slot kind="30" offset="-84"/> <slot kind="21" offset="-84"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="5" startColumn="84" endLine="5" endColumn="95" document="1"/> <entry offset="0x1" hidden="true" document="1"/> <entry offset="0xe" startLine="5" startColumn="96" endLine="5" endColumn="112" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x1f"> <importsforward declaringType="M" methodName=".cctor"/> <local name="$VB$Closure_0" il_index="0" il_start="0x0" il_end="0x1f" attributes="0"/> </scope> </method> </methods> </symbols>) End Sub <WorkItem(846228, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/846228")> <WorkItem(845078, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/845078")> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub RaiseEvent001() Dim source = <compilation> <file><![CDATA[ Public Class IntervalUpdate Public Shared Sub Update() RaiseEvent IntervalElapsed() End Sub Shared Sub Main() Update() End Sub Public Shared Event IntervalElapsed() End Class ]]></file> </compilation> Dim defines = PredefinedPreprocessorSymbols.AddPredefinedPreprocessorSymbols(OutputKind.ConsoleApplication) defines = defines.Add(KeyValuePairUtil.Create("_MyType", CObj("Console"))) Dim parseOptions = New VisualBasicParseOptions(preprocessorSymbols:=defines) Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugDll.WithParseOptions(parseOptions)) CompileAndVerify(compilation).VerifyIL("IntervalUpdate.Update", " { // Code size 18 (0x12) .maxstack 1 .locals init (IntervalUpdate.IntervalElapsedEventHandler V_0) -IL_0000: nop -IL_0001: ldsfld ""IntervalUpdate.IntervalElapsedEvent As IntervalUpdate.IntervalElapsedEventHandler"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0011 IL_000a: ldloc.0 IL_000b: callvirt ""Sub IntervalUpdate.IntervalElapsedEventHandler.Invoke()"" IL_0010: nop -IL_0011: ret } ", sequencePoints:="IntervalUpdate.Update") compilation.VerifyPdb( <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="My.MyComputer" name=".ctor"> <sequencePoints> <entry offset="0x0" startLine="109" startColumn="9" endLine="109" endColumn="25" document="1"/> <entry offset="0x1" startLine="110" startColumn="13" endLine="110" endColumn="25" document="1"/> <entry offset="0x8" startLine="111" startColumn="9" endLine="111" endColumn="16" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x9"> <currentnamespace name="My"/> </scope> </method> <method containingType="My.MyProject" name=".cctor"> <sequencePoints> <entry offset="0x0" startLine="128" startColumn="26" endLine="128" endColumn="97" document="1"/> <entry offset="0xa" startLine="139" startColumn="26" endLine="139" endColumn="95" document="1"/> <entry offset="0x14" startLine="150" startColumn="26" endLine="150" endColumn="136" document="1"/> <entry offset="0x1e" startLine="286" startColumn="26" endLine="286" endColumn="105" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x29"> <importsforward declaringType="My.MyComputer" methodName=".ctor"/> </scope> </method> <method containingType="My.MyProject" name="get_Computer"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="123" startColumn="13" endLine="123" endColumn="16" document="1"/> <entry offset="0x1" startLine="124" startColumn="17" endLine="124" endColumn="62" document="1"/> <entry offset="0xe" startLine="125" startColumn="13" endLine="125" endColumn="20" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x10"> <importsforward declaringType="My.MyComputer" methodName=".ctor"/> <local name="Computer" il_index="0" il_start="0x0" il_end="0x10" attributes="0"/> </scope> </method> <method containingType="My.MyProject" name="get_Application"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="135" startColumn="13" endLine="135" endColumn="16" document="1"/> <entry offset="0x1" startLine="136" startColumn="17" endLine="136" endColumn="57" document="1"/> <entry offset="0xe" startLine="137" startColumn="13" endLine="137" endColumn="20" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x10"> <importsforward declaringType="My.MyComputer" methodName=".ctor"/> <local name="Application" il_index="0" il_start="0x0" il_end="0x10" attributes="0"/> </scope> </method> <method containingType="My.MyProject" name="get_User"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="146" startColumn="13" endLine="146" endColumn="16" document="1"/> <entry offset="0x1" startLine="147" startColumn="17" endLine="147" endColumn="58" document="1"/> <entry offset="0xe" startLine="148" startColumn="13" endLine="148" endColumn="20" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x10"> <importsforward declaringType="My.MyComputer" methodName=".ctor"/> <local name="User" il_index="0" il_start="0x0" il_end="0x10" attributes="0"/> </scope> </method> <method containingType="My.MyProject" name="get_WebServices"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="239" startColumn="14" endLine="239" endColumn="17" document="1"/> <entry offset="0x1" startLine="240" startColumn="17" endLine="240" endColumn="67" document="1"/> <entry offset="0xe" startLine="241" startColumn="13" endLine="241" endColumn="20" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x10"> <importsforward declaringType="My.MyComputer" methodName=".ctor"/> <local name="WebServices" il_index="0" il_start="0x0" il_end="0x10" attributes="0"/> </scope> </method> <method containingType="IntervalUpdate" name="Update"> <sequencePoints> <entry offset="0x0" startLine="2" startColumn="5" endLine="2" endColumn="31" document="1"/> <entry offset="0x1" startLine="3" startColumn="9" endLine="3" endColumn="37" document="1"/> <entry offset="0x11" startLine="4" startColumn="5" endLine="4" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x12"> <currentnamespace name=""/> </scope> </method> <method containingType="IntervalUpdate" name="Main"> <sequencePoints> <entry offset="0x0" startLine="6" startColumn="5" endLine="6" endColumn="22" document="1"/> <entry offset="0x1" startLine="7" startColumn="9" endLine="7" endColumn="17" document="1"/> <entry offset="0x7" startLine="8" startColumn="5" endLine="8" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x8"> <importsforward declaringType="IntervalUpdate" methodName="Update"/> </scope> </method> <method containingType="My.MyProject+MyWebServices" name="Equals" parameterNames="o"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="249" startColumn="13" endLine="249" endColumn="75" document="1"/> <entry offset="0x1" startLine="250" startColumn="17" endLine="250" endColumn="40" document="1"/> <entry offset="0x10" startLine="251" startColumn="13" endLine="251" endColumn="25" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x12"> <currentnamespace name="My"/> <local name="Equals" il_index="0" il_start="0x0" il_end="0x12" attributes="0"/> </scope> </method> <method containingType="My.MyProject+MyWebServices" name="GetHashCode"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="253" startColumn="13" endLine="253" endColumn="63" document="1"/> <entry offset="0x1" startLine="254" startColumn="17" endLine="254" endColumn="42" document="1"/> <entry offset="0xa" startLine="255" startColumn="13" endLine="255" endColumn="25" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0xc"> <importsforward declaringType="My.MyProject+MyWebServices" methodName="Equals" parameterNames="o"/> <local name="GetHashCode" il_index="0" il_start="0x0" il_end="0xc" attributes="0"/> </scope> </method> <method containingType="My.MyProject+MyWebServices" name="GetType"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="257" startColumn="13" endLine="257" endColumn="72" document="1"/> <entry offset="0x1" startLine="258" startColumn="17" endLine="258" endColumn="46" document="1"/> <entry offset="0xe" startLine="259" startColumn="13" endLine="259" endColumn="25" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x10"> <importsforward declaringType="My.MyProject+MyWebServices" methodName="Equals" parameterNames="o"/> <local name="GetType" il_index="0" il_start="0x0" il_end="0x10" attributes="0"/> </scope> </method> <method containingType="My.MyProject+MyWebServices" name="ToString"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="261" startColumn="13" endLine="261" endColumn="59" document="1"/> <entry offset="0x1" startLine="262" startColumn="17" endLine="262" endColumn="39" document="1"/> <entry offset="0xa" startLine="263" startColumn="13" endLine="263" endColumn="25" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0xc"> <importsforward declaringType="My.MyProject+MyWebServices" methodName="Equals" parameterNames="o"/> <local name="ToString" il_index="0" il_start="0x0" il_end="0xc" attributes="0"/> </scope> </method> <method containingType="My.MyProject+MyWebServices" name="Create__Instance__" parameterNames="instance"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> <slot kind="1" offset="0"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="266" startColumn="12" endLine="266" endColumn="95" document="1"/> <entry offset="0x1" startLine="267" startColumn="17" endLine="267" endColumn="44" document="1"/> <entry offset="0xb" hidden="true" document="1"/> <entry offset="0xe" startLine="268" startColumn="21" endLine="268" endColumn="35" document="1"/> <entry offset="0x16" startLine="269" startColumn="17" endLine="269" endColumn="21" document="1"/> <entry offset="0x17" startLine="270" startColumn="21" endLine="270" endColumn="36" document="1"/> <entry offset="0x1b" startLine="272" startColumn="13" endLine="272" endColumn="25" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x1d"> <importsforward declaringType="My.MyProject+MyWebServices" methodName="Equals" parameterNames="o"/> <local name="Create__Instance__" il_index="0" il_start="0x0" il_end="0x1d" attributes="0"/> </scope> </method> <method containingType="My.MyProject+MyWebServices" name="Dispose__Instance__" parameterNames="instance"> <sequencePoints> <entry offset="0x0" startLine="275" startColumn="13" endLine="275" endColumn="71" document="1"/> <entry offset="0x1" startLine="276" startColumn="17" endLine="276" endColumn="35" document="1"/> <entry offset="0x8" startLine="277" startColumn="13" endLine="277" endColumn="20" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x9"> <importsforward declaringType="My.MyProject+MyWebServices" methodName="Equals" parameterNames="o"/> </scope> </method> <method containingType="My.MyProject+MyWebServices" name=".ctor"> <sequencePoints> <entry offset="0x0" startLine="281" startColumn="13" endLine="281" endColumn="29" document="1"/> <entry offset="0x1" startLine="282" startColumn="16" endLine="282" endColumn="28" document="1"/> <entry offset="0x8" startLine="283" startColumn="13" endLine="283" endColumn="20" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x9"> <importsforward declaringType="My.MyProject+MyWebServices" methodName="Equals" parameterNames="o"/> </scope> </method> <method containingType="My.MyProject+ThreadSafeObjectProvider`1" name="get_GetInstance"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> <slot kind="1" offset="0"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="343" startColumn="17" endLine="343" endColumn="20" document="1"/> <entry offset="0x1" startLine="344" startColumn="21" endLine="344" endColumn="59" document="1"/> <entry offset="0xf" hidden="true" document="1"/> <entry offset="0x12" startLine="344" startColumn="60" endLine="344" endColumn="87" document="1"/> <entry offset="0x1c" startLine="345" startColumn="21" endLine="345" endColumn="47" document="1"/> <entry offset="0x24" startLine="346" startColumn="17" endLine="346" endColumn="24" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x26"> <importsforward declaringType="My.MyProject+MyWebServices" methodName="Equals" parameterNames="o"/> <local name="GetInstance" il_index="0" il_start="0x0" il_end="0x26" attributes="0"/> </scope> </method> <method containingType="My.MyProject+ThreadSafeObjectProvider`1" name=".ctor"> <sequencePoints> <entry offset="0x0" startLine="352" startColumn="13" endLine="352" endColumn="29" document="1"/> <entry offset="0x1" startLine="353" startColumn="17" endLine="353" endColumn="29" document="1"/> <entry offset="0x8" startLine="354" startColumn="13" endLine="354" endColumn="20" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x9"> <importsforward declaringType="My.MyProject+MyWebServices" methodName="Equals" parameterNames="o"/> </scope> </method> </methods> </symbols>, options:=PdbValidationOptions.SkipConversionValidation) ' TODO: https://github.com/dotnet/roslyn/issues/18004 End Sub <WorkItem(876518, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/876518")> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub WinFormMain() Dim source = <compilation> <file> &lt;Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()&gt; _ Partial Class Form1 Inherits System.Windows.Forms.Form 'Form overrides dispose to clean up the component list. &lt;System.Diagnostics.DebuggerNonUserCode()&gt; _ Protected Overrides Sub Dispose(ByVal disposing As Boolean) Try If disposing AndAlso components IsNot Nothing Then components.Dispose() End If Finally MyBase.Dispose(disposing) End Try End Sub 'Required by the Windows Form Designer Private components As System.ComponentModel.IContainer 'NOTE: The following procedure is required by the Windows Form Designer 'It can be modified using the Windows Form Designer. 'Do not modify it using the code editor. &lt;System.Diagnostics.DebuggerStepThrough()&gt; _ Private Sub InitializeComponent() components = New System.ComponentModel.Container() Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font Me.Text = "Form1" End Sub End Class </file> </compilation> Dim defines = PredefinedPreprocessorSymbols.AddPredefinedPreprocessorSymbols( OutputKind.WindowsApplication, KeyValuePairUtil.Create(Of String, Object)("_MyType", "WindowsForms"), KeyValuePairUtil.Create(Of String, Object)("Config", "Debug"), KeyValuePairUtil.Create(Of String, Object)("DEBUG", -1), KeyValuePairUtil.Create(Of String, Object)("TRACE", -1), KeyValuePairUtil.Create(Of String, Object)("PLATFORM", "AnyCPU")) Dim parseOptions As VisualBasicParseOptions = New VisualBasicParseOptions(preprocessorSymbols:=defines) Dim compOptions As VisualBasicCompilationOptions = New VisualBasicCompilationOptions( OutputKind.WindowsApplication, optimizationLevel:=OptimizationLevel.Debug, parseOptions:=parseOptions, mainTypeName:="My.MyApplication") Dim comp = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, {SystemWindowsFormsRef}, compOptions) comp.VerifyDiagnostics() ' Just care that there's at least one non-hidden sequence point. comp.VerifyPdb("My.MyApplication.Main", <symbols> <files> <file id="1" name="" language="VB"/> </files> <entryPoint declaringType="My.MyApplication" methodName="Main" parameterNames="Args"/> <methods> <method containingType="My.MyApplication" name="Main" parameterNames="Args"> <sequencePoints> <entry offset="0x0" startLine="78" startColumn="9" endLine="78" endColumn="55" document="1"/> <entry offset="0x1" startLine="79" startColumn="13" endLine="79" endColumn="16" document="1"/> <entry offset="0x2" startLine="80" startColumn="16" endLine="80" endColumn="133" document="1"/> <entry offset="0xf" startLine="81" startColumn="13" endLine="81" endColumn="20" document="1"/> <entry offset="0x11" startLine="82" startColumn="13" endLine="82" endColumn="20" document="1"/> <entry offset="0x12" startLine="83" startColumn="13" endLine="83" endColumn="37" document="1"/> <entry offset="0x1e" startLine="84" startColumn="9" endLine="84" endColumn="16" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x1f"> <currentnamespace name="My"/> </scope> </method> </methods> </symbols>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub SynthesizedVariableForSelectCastValue() Dim source = <compilation> <file> Imports System Class C Sub F(args As String()) Select Case args(0) Case "a" Console.WriteLine(1) Case "b" Console.WriteLine(2) Case "c" Console.WriteLine(3) End Select End Sub End Class </file> </compilation> Dim c = CreateCompilationWithMscorlib40AndVBRuntime(source, options:=TestOptions.DebugDll) c.VerifyDiagnostics() c.VerifyPdb("C.F", <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="C" name="F" parameterNames="args"> <customDebugInfo> <encLocalSlotMap> <slot kind="15" offset="0"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="3" startColumn="5" endLine="3" endColumn="28" document="1"/> <entry offset="0x1" startLine="4" startColumn="9" endLine="4" endColumn="28" document="1"/> <entry offset="0x32" startLine="5" startColumn="13" endLine="5" endColumn="21" document="1"/> <entry offset="0x33" startLine="6" startColumn="17" endLine="6" endColumn="37" document="1"/> <entry offset="0x3c" startLine="7" startColumn="13" endLine="7" endColumn="21" document="1"/> <entry offset="0x3d" startLine="8" startColumn="17" endLine="8" endColumn="37" document="1"/> <entry offset="0x46" startLine="9" startColumn="13" endLine="9" endColumn="21" document="1"/> <entry offset="0x47" startLine="10" startColumn="17" endLine="10" endColumn="37" document="1"/> <entry offset="0x50" startLine="11" startColumn="9" endLine="11" endColumn="19" document="1"/> <entry offset="0x51" startLine="12" startColumn="5" endLine="12" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x52"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> </scope> </method> </methods> </symbols>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub Constant_AllTypes() Dim source = <compilation> <file> Imports System Imports System.Collections.Generic 'Imports Microsoft.VisualBasic.Strings Class X End Class Public Class C(Of S) Enum EnumI1 As SByte : A : End Enum Enum EnumU1 As Byte : A : End Enum Enum EnumI2 As Short : A : End Enum Enum EnumU2 As UShort : A : End Enum Enum EnumI4 As Integer : A : End Enum Enum EnumU4 As UInteger : A : End Enum Enum EnumI8 As Long : A : End Enum Enum EnumU8 As ULong : A : End Enum Public Sub F(Of T)() Const B As Boolean = Nothing Const C As Char = Nothing Const I1 As SByte = 0 Const U1 As Byte = 0 Const I2 As Short = 0 Const U2 As UShort = 0 Const I4 As Integer = 0 Const U4 As UInteger = 0 Const I8 As Long = 0 Const U8 As ULong = 0 Const R4 As Single = 0 Const R8 As Double = 0 Const EI1 As C(Of Integer).EnumI1 = 0 Const EU1 As C(Of Integer).EnumU1 = 0 Const EI2 As C(Of Integer).EnumI2 = 0 Const EU2 As C(Of Integer).EnumU2 = 0 Const EI4 As C(Of Integer).EnumI4 = 0 Const EU4 As C(Of Integer).EnumU4 = 0 Const EI8 As C(Of Integer).EnumI8 = 0 Const EU8 As C(Of Integer).EnumU8 = 0 'Const StrWithNul As String = ChrW(0) Const EmptyStr As String = "" Const NullStr As String = Nothing Const NullObject As Object = Nothing Const D As Decimal = Nothing Const DT As DateTime = #1-1-2015# End Sub End Class </file> </compilation> Dim c = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, {SystemCoreRef}, options:=TestOptions.DebugDll.WithEmbedVbCoreRuntime(True)) c.VerifyPdb("C`1.F", <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="C`1" name="F"> <sequencePoints> <entry offset="0x0" startLine="18" startColumn="5" endLine="18" endColumn="25" document="1"/> <entry offset="0x1" startLine="48" startColumn="5" endLine="48" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x2"> <namespace name="System" importlevel="file"/> <namespace name="System.Collections.Generic" importlevel="file"/> <currentnamespace name=""/> <constant name="B" value="0" type="Boolean"/> <constant name="C" value="0" type="Char"/> <constant name="I1" value="0" type="SByte"/> <constant name="U1" value="0" type="Byte"/> <constant name="I2" value="0" type="Int16"/> <constant name="U2" value="0" type="UInt16"/> <constant name="I4" value="0" type="Int32"/> <constant name="U4" value="0" type="UInt32"/> <constant name="I8" value="0" type="Int64"/> <constant name="U8" value="0" type="UInt64"/> <constant name="R4" value="0x00000000" type="Single"/> <constant name="R8" value="0x0000000000000000" type="Double"/> <constant name="EI1" value="0" signature="EnumI1{Int32}"/> <constant name="EU1" value="0" signature="EnumU1{Int32}"/> <constant name="EI2" value="0" signature="EnumI2{Int32}"/> <constant name="EU2" value="0" signature="EnumU2{Int32}"/> <constant name="EI4" value="0" signature="EnumI4{Int32}"/> <constant name="EU4" value="0" signature="EnumU4{Int32}"/> <constant name="EI8" value="0" signature="EnumI8{Int32}"/> <constant name="EU8" value="0" signature="EnumU8{Int32}"/> <constant name="EmptyStr" value="" type="String"/> <constant name="NullStr" value="null" type="String"/> <constant name="NullObject" value="null" type="Object"/> <constant name="D" value="0" type="Decimal"/> <constant name="DT" value="01/01/2015 00:00:00" type="DateTime"/> </scope> </method> </methods> </symbols>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub ImportsInAsync() Dim source = "Imports System.Linq Imports System.Threading.Tasks Class C Shared Async Function F() As Task Dim c = {1, 2, 3} c.Select(Function(i) i) End Function End Class" Dim c = CreateCompilationWithMscorlib45AndVBRuntime({Parse(source)}, options:=TestOptions.DebugDll, references:={SystemCoreRef}) c.VerifyPdb("C+VB$StateMachine_1_F.MoveNext", <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="C+VB$StateMachine_1_F" name="MoveNext"> <customDebugInfo> <hoistedLocalScopes format="portable"> <slot startOffset="0x0" endOffset="0x8b"/> </hoistedLocalScopes> <encLocalSlotMap> <slot kind="27" offset="-1"/> <slot kind="temp"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" hidden="true" document="1"/> <entry offset="0x7" startLine="4" startColumn="5" endLine="4" endColumn="38" document="1"/> <entry offset="0x8" startLine="5" startColumn="13" endLine="5" endColumn="26" document="1"/> <entry offset="0x1f" startLine="6" startColumn="9" endLine="6" endColumn="32" document="1"/> <entry offset="0x4f" startLine="7" startColumn="5" endLine="7" endColumn="17" document="1"/> <entry offset="0x51" hidden="true" document="1"/> <entry offset="0x58" hidden="true" document="1"/> <entry offset="0x74" startLine="7" startColumn="5" endLine="7" endColumn="17" document="1"/> <entry offset="0x7e" hidden="true" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x8b"> <importsforward declaringType="C+_Closure$__" methodName="_Lambda$__1-0" parameterNames="i"/> <local name="$VB$ResumableLocal_c$0" il_index="0" il_start="0x0" il_end="0x8b" attributes="0"/> </scope> <asyncInfo> <kickoffMethod declaringType="C" methodName="F"/> </asyncInfo> </method> </methods> </symbols>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub ImportsInAsyncLambda() Dim source = "Imports System.Linq Class C Shared Sub M() Dim f As System.Action = Async Sub() Dim c = {1, 2, 3} c.Select(Function(i) i) End Sub End Sub End Class" Dim c = CreateCompilationWithMscorlib45AndVBRuntime({Parse(source)}, options:=TestOptions.DebugDll, references:={SystemCoreRef}) c.VerifyPdb("C+_Closure$__+VB$StateMachine___Lambda$__1-0.MoveNext", <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="C+_Closure$__+VB$StateMachine___Lambda$__1-0" name="MoveNext"> <customDebugInfo> <hoistedLocalScopes format="portable"> <slot startOffset="0x0" endOffset="0x8b"/> </hoistedLocalScopes> <encLocalSlotMap> <slot kind="27" offset="38"/> <slot kind="temp"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" hidden="true" document="1"/> <entry offset="0x7" startLine="5" startColumn="13" endLine="5" endColumn="24" document="1"/> <entry offset="0x8" startLine="6" startColumn="21" endLine="6" endColumn="34" document="1"/> <entry offset="0x1f" startLine="7" startColumn="17" endLine="7" endColumn="40" document="1"/> <entry offset="0x4f" startLine="8" startColumn="13" endLine="8" endColumn="20" document="1"/> <entry offset="0x51" hidden="true" document="1"/> <entry offset="0x58" hidden="true" document="1"/> <entry offset="0x74" hidden="true" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x8b"> <importsforward declaringType="C" methodName="M"/> <local name="$VB$ResumableLocal_c$0" il_index="0" il_start="0x0" il_end="0x8b" attributes="0"/> </scope> <asyncInfo> <catchHandler offset="0x51"/> <kickoffMethod declaringType="C+_Closure$__" methodName="_Lambda$__1-0"/> </asyncInfo> </method> </methods> </symbols>) End Sub <ConditionalFact(GetType(WindowsDesktopOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> <WorkItem(23525, "https://github.com/dotnet/roslyn/issues/23525")> Public Sub InvalidCharacterInPdbPath() Using outStream = Temp.CreateFile().Open() Dim Compilation = CreateEmptyCompilation("") Dim result = Compilation.Emit(outStream, options:=New EmitOptions(pdbFilePath:="test\\?.pdb", debugInformationFormat:=DebugInformationFormat.Embedded)) ' This is fine because EmitOptions just controls what is written into the PE file and it's ' valid for this to be an illegal file name (path map can easily create these). Assert.True(result.Success) End Using End Sub <ConditionalFact(GetType(WindowsDesktopOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> <WorkItem(38954, "https://github.com/dotnet/roslyn/issues/38954")> Public Sub FilesOneWithNoMethodBody() Dim source1 = "Imports System Class C Public Shared Sub Main() Console.WriteLine() End Sub End Class " Dim source2 = " ' no code " Dim tree1 = Parse(source1, "f:/build/goo.vb") Dim tree2 = Parse(source2, "f:/build/nocode.vb") Dim c = CreateCompilation({tree1, tree2}, options:=TestOptions.DebugDll) c.VerifyPdb(" <symbols> <files> <file id=""1"" name=""f:/build/goo.vb"" language=""VB"" checksumAlgorithm=""SHA1"" checksum=""48-27-3C-50-9D-24-D4-0D-51-87-6C-E2-FB-2F-AA-1C-80-96-0B-B7"" /> <file id=""2"" name=""f:/build/nocode.vb"" language=""VB"" checksumAlgorithm=""SHA1"" checksum=""40-43-2C-44-BA-1C-C7-1A-B3-F3-68-E5-96-7C-65-9D-61-85-D5-44"" /> </files> <methods> <method containingType=""C"" name=""Main""> <sequencePoints> <entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""29"" document=""1"" /> <entry offset=""0x1"" startLine=""5"" startColumn=""9"" endLine=""5"" endColumn=""28"" document=""1"" /> <entry offset=""0x7"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""12"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x8""> <namespace name=""System"" importlevel=""file"" /> <currentnamespace name="""" /> </scope> </method> </methods> </symbols> ") End Sub <ConditionalFact(GetType(WindowsDesktopOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> <WorkItem(38954, "https://github.com/dotnet/roslyn/issues/38954")> Public Sub SingleFileWithNoMethodBody() Dim source = " ' no code " Dim tree = Parse(source, "f:/build/nocode.vb") Dim c = CreateCompilation({tree}, options:=TestOptions.DebugDll) c.VerifyPdb(" <symbols> <files> <file id=""1"" name=""f:/build/nocode.vb"" language=""VB"" checksumAlgorithm=""SHA1"" checksum=""40-43-2C-44-BA-1C-C7-1A-B3-F3-68-E5-96-7C-65-9D-61-85-D5-44"" /> </files> <methods /> </symbols> ") 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.IO Imports System.Reflection.Metadata Imports System.Reflection.Metadata.Ecma335 Imports System.Reflection.PortableExecutable Imports System.Text Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.PDB Public Class PDBTests Inherits BasicTestBase #Region "General" <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub EmitDebugInfoForSourceTextWithoutEncoding1() Dim tree1 = SyntaxFactory.ParseSyntaxTree("Class A : End Class", path:="Goo.vb", encoding:=Nothing) Dim tree2 = SyntaxFactory.ParseSyntaxTree("Class B : End Class", path:="", encoding:=Nothing) Dim tree3 = SyntaxFactory.ParseSyntaxTree(SourceText.From("Class C : End Class", encoding:=Nothing), path:="Bar.vb") Dim tree4 = SyntaxFactory.ParseSyntaxTree("Class D : End Class", path:="Baz.vb", encoding:=Encoding.UTF8) Dim comp = VisualBasicCompilation.Create("Compilation", {tree1, tree2, tree3, tree4}, {MscorlibRef}, options:=TestOptions.ReleaseDll) Dim result = comp.Emit(New MemoryStream(), pdbStream:=New MemoryStream()) result.Diagnostics.Verify( Diagnostic(ERRID.ERR_EncodinglessSyntaxTree, "Class A : End Class").WithLocation(1, 1), Diagnostic(ERRID.ERR_EncodinglessSyntaxTree, "Class C : End Class").WithLocation(1, 1)) Assert.False(result.Success) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub EmitDebugInfoForSourceTextWithoutEncoding2() Dim tree1 = SyntaxFactory.ParseSyntaxTree("Class A" & vbCrLf & "Sub F() : End Sub : End Class", path:="Goo.vb", encoding:=Encoding.Unicode) Dim tree2 = SyntaxFactory.ParseSyntaxTree("Class B" & vbCrLf & "Sub F() : End Sub : End Class", path:="", encoding:=Nothing) Dim tree3 = SyntaxFactory.ParseSyntaxTree("Class C" & vbCrLf & "Sub F() : End Sub : End Class", path:="Bar.vb", encoding:=New UTF8Encoding(True, False)) Dim tree4 = SyntaxFactory.ParseSyntaxTree(SourceText.From("Class D" & vbCrLf & "Sub F() : End Sub : End Class", New UTF8Encoding(False, False)), path:="Baz.vb") Dim comp = VisualBasicCompilation.Create("Compilation", {tree1, tree2, tree3, tree4}, {MscorlibRef}, options:=TestOptions.ReleaseDll) Dim result = comp.Emit(New MemoryStream(), pdbStream:=New MemoryStream()) result.Diagnostics.Verify() Assert.True(result.Success) Dim hash1 = CryptographicHashProvider.ComputeSha1(Encoding.Unicode.GetBytesWithPreamble(tree1.ToString())).ToArray() Dim hash3 = CryptographicHashProvider.ComputeSha1(New UTF8Encoding(True, False).GetBytesWithPreamble(tree3.ToString())).ToArray() Dim hash4 = CryptographicHashProvider.ComputeSha1(New UTF8Encoding(False, False).GetBytesWithPreamble(tree4.ToString())).ToArray() comp.VerifyPdb( <symbols> <files> <file id="1" name="Goo.vb" language="VB" checksumAlgorithm="SHA1" checksum=<%= BitConverter.ToString(hash1) %>/> <file id="2" name="" language="VB"/> <file id="3" name="Bar.vb" language="VB" checksumAlgorithm="SHA1" checksum=<%= BitConverter.ToString(hash3) %>/> <file id="4" name="Baz.vb" language="VB" checksumAlgorithm="SHA1" checksum=<%= BitConverter.ToString(hash4) %>/> </files> </symbols>, options:=PdbValidationOptions.ExcludeMethods) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub CustomDebugEntryPoint_DLL() Dim source = " Class C Shared Sub F() End Sub End Class " Dim c = CreateCompilationWithMscorlib40({source}, options:=TestOptions.DebugDll) Dim f = c.GetMember(Of MethodSymbol)("C.F") c.VerifyPdb( <symbols> <files> <file id="1" name="" language="VB"/> </files> <entryPoint declaringType="C" methodName="F"/> <methods/> </symbols>, debugEntryPoint:=f, options:=PdbValidationOptions.ExcludeScopes Or PdbValidationOptions.ExcludeSequencePoints Or PdbValidationOptions.ExcludeCustomDebugInformation) Dim peReader = New PEReader(c.EmitToArray(debugEntryPoint:=f)) Dim peEntryPointToken = peReader.PEHeaders.CorHeader.EntryPointTokenOrRelativeVirtualAddress Assert.Equal(0, peEntryPointToken) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub CustomDebugEntryPoint_EXE() Dim source = " Class M Shared Sub Main() End Sub End Class Class C Shared Sub F(Of S)() End Sub End Class " Dim c = CreateCompilationWithMscorlib40({source}, options:=TestOptions.DebugExe) Dim f = c.GetMember(Of MethodSymbol)("C.F") c.VerifyPdb( <symbols> <files> <file id="1" name="" language="VB"/> </files> <entryPoint declaringType="C" methodName="F"/> <methods/> </symbols>, debugEntryPoint:=f, options:=PdbValidationOptions.ExcludeScopes Or PdbValidationOptions.ExcludeSequencePoints Or PdbValidationOptions.ExcludeCustomDebugInformation) Dim peReader = New PEReader(c.EmitToArray(debugEntryPoint:=f)) Dim peEntryPointToken = peReader.PEHeaders.CorHeader.EntryPointTokenOrRelativeVirtualAddress Dim mdReader = peReader.GetMetadataReader() Dim methodDef = mdReader.GetMethodDefinition(CType(MetadataTokens.Handle(peEntryPointToken), MethodDefinitionHandle)) Assert.Equal("Main", mdReader.GetString(methodDef.Name)) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub CustomDebugEntryPoint_Errors() Dim source1 = " Class C Shared Sub F End Sub End Class Class D(Of T) Shared Sub G(Of S)() End Sub End Class " Dim source2 = " Class C Shared Sub F() End Sub End Class " Dim c1 = CreateCompilationWithMscorlib40({source1}, options:=TestOptions.DebugDll) Dim c2 = CreateCompilationWithMscorlib40({source2}, options:=TestOptions.DebugDll) Dim f1 = c1.GetMember(Of MethodSymbol)("C.F") Dim f2 = c2.GetMember(Of MethodSymbol)("C.F") Dim g = c1.GetMember(Of MethodSymbol)("D.G") Dim d = c1.GetMember(Of NamedTypeSymbol)("D") Assert.NotNull(f1) Assert.NotNull(f2) Assert.NotNull(g) Assert.NotNull(d) Dim stInt = c1.GetSpecialType(SpecialType.System_Int32) Dim d_t_g_int = g.Construct(stInt) Dim d_int = d.Construct(stInt) Dim d_int_g = d_int.GetMember(Of MethodSymbol)("G") Dim d_int_g_int = d_int_g.Construct(stInt) Dim result = c1.Emit(New MemoryStream(), New MemoryStream(), debugEntryPoint:=f2) result.Diagnostics.Verify(Diagnostic(ERRID.ERR_DebugEntryPointNotSourceMethodDefinition)) result = c1.Emit(New MemoryStream(), New MemoryStream(), debugEntryPoint:=d_t_g_int) result.Diagnostics.Verify(Diagnostic(ERRID.ERR_DebugEntryPointNotSourceMethodDefinition)) result = c1.Emit(New MemoryStream(), New MemoryStream(), debugEntryPoint:=d_int_g) result.Diagnostics.Verify(Diagnostic(ERRID.ERR_DebugEntryPointNotSourceMethodDefinition)) result = c1.Emit(New MemoryStream(), New MemoryStream(), debugEntryPoint:=d_int_g_int) result.Diagnostics.Verify(Diagnostic(ERRID.ERR_DebugEntryPointNotSourceMethodDefinition)) End Sub #End Region <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub TestBasic() Dim source = <compilation> <file><![CDATA[ Class C1 Sub Method() System.Console.WriteLine("Hello, world.") End Sub End Class ]]></file> </compilation> Dim defines = PredefinedPreprocessorSymbols.AddPredefinedPreprocessorSymbols(OutputKind.ConsoleApplication) defines = defines.Add(KeyValuePairUtil.Create("_MyType", CObj("Console"))) Dim parseOptions = New VisualBasicParseOptions(preprocessorSymbols:=defines) Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugDll.WithParseOptions(parseOptions)) compilation.VerifyPdb( <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="My.MyComputer" name=".ctor"> <sequencePoints> <entry offset="0x0" startLine="109" startColumn="9" endLine="109" endColumn="25" document="1"/> <entry offset="0x1" startLine="110" startColumn="13" endLine="110" endColumn="25" document="1"/> <entry offset="0x8" startLine="111" startColumn="9" endLine="111" endColumn="16" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x9"> <currentnamespace name="My"/> </scope> </method> <method containingType="My.MyProject" name=".cctor"> <sequencePoints> <entry offset="0x0" startLine="128" startColumn="26" endLine="128" endColumn="97" document="1"/> <entry offset="0xa" startLine="139" startColumn="26" endLine="139" endColumn="95" document="1"/> <entry offset="0x14" startLine="150" startColumn="26" endLine="150" endColumn="136" document="1"/> <entry offset="0x1e" startLine="286" startColumn="26" endLine="286" endColumn="105" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x29"> <importsforward declaringType="My.MyComputer" methodName=".ctor"/> </scope> </method> <method containingType="My.MyProject" name="get_Computer"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="123" startColumn="13" endLine="123" endColumn="16" document="1"/> <entry offset="0x1" startLine="124" startColumn="17" endLine="124" endColumn="62" document="1"/> <entry offset="0xe" startLine="125" startColumn="13" endLine="125" endColumn="20" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x10"> <importsforward declaringType="My.MyComputer" methodName=".ctor"/> <local name="Computer" il_index="0" il_start="0x0" il_end="0x10" attributes="0"/> </scope> </method> <method containingType="My.MyProject" name="get_Application"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="135" startColumn="13" endLine="135" endColumn="16" document="1"/> <entry offset="0x1" startLine="136" startColumn="17" endLine="136" endColumn="57" document="1"/> <entry offset="0xe" startLine="137" startColumn="13" endLine="137" endColumn="20" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x10"> <importsforward declaringType="My.MyComputer" methodName=".ctor"/> <local name="Application" il_index="0" il_start="0x0" il_end="0x10" attributes="0"/> </scope> </method> <method containingType="My.MyProject" name="get_User"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="146" startColumn="13" endLine="146" endColumn="16" document="1"/> <entry offset="0x1" startLine="147" startColumn="17" endLine="147" endColumn="58" document="1"/> <entry offset="0xe" startLine="148" startColumn="13" endLine="148" endColumn="20" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x10"> <importsforward declaringType="My.MyComputer" methodName=".ctor"/> <local name="User" il_index="0" il_start="0x0" il_end="0x10" attributes="0"/> </scope> </method> <method containingType="My.MyProject" name="get_WebServices"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="239" startColumn="14" endLine="239" endColumn="17" document="1"/> <entry offset="0x1" startLine="240" startColumn="17" endLine="240" endColumn="67" document="1"/> <entry offset="0xe" startLine="241" startColumn="13" endLine="241" endColumn="20" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x10"> <importsforward declaringType="My.MyComputer" methodName=".ctor"/> <local name="WebServices" il_index="0" il_start="0x0" il_end="0x10" attributes="0"/> </scope> </method> <method containingType="C1" name="Method"> <sequencePoints> <entry offset="0x0" startLine="2" startColumn="5" endLine="2" endColumn="17" document="1"/> <entry offset="0x1" startLine="3" startColumn="9" endLine="3" endColumn="50" document="1"/> <entry offset="0xc" startLine="4" startColumn="5" endLine="4" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0xd"> <currentnamespace name=""/> </scope> </method> <method containingType="My.MyProject+MyWebServices" name="Equals" parameterNames="o"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="249" startColumn="13" endLine="249" endColumn="75" document="1"/> <entry offset="0x1" startLine="250" startColumn="17" endLine="250" endColumn="40" document="1"/> <entry offset="0x10" startLine="251" startColumn="13" endLine="251" endColumn="25" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x12"> <currentnamespace name="My"/> <local name="Equals" il_index="0" il_start="0x0" il_end="0x12" attributes="0"/> </scope> </method> <method containingType="My.MyProject+MyWebServices" name="GetHashCode"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="253" startColumn="13" endLine="253" endColumn="63" document="1"/> <entry offset="0x1" startLine="254" startColumn="17" endLine="254" endColumn="42" document="1"/> <entry offset="0xa" startLine="255" startColumn="13" endLine="255" endColumn="25" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0xc"> <importsforward declaringType="My.MyProject+MyWebServices" methodName="Equals" parameterNames="o"/> <local name="GetHashCode" il_index="0" il_start="0x0" il_end="0xc" attributes="0"/> </scope> </method> <method containingType="My.MyProject+MyWebServices" name="GetType"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="257" startColumn="13" endLine="257" endColumn="72" document="1"/> <entry offset="0x1" startLine="258" startColumn="17" endLine="258" endColumn="46" document="1"/> <entry offset="0xe" startLine="259" startColumn="13" endLine="259" endColumn="25" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x10"> <importsforward declaringType="My.MyProject+MyWebServices" methodName="Equals" parameterNames="o"/> <local name="GetType" il_index="0" il_start="0x0" il_end="0x10" attributes="0"/> </scope> </method> <method containingType="My.MyProject+MyWebServices" name="ToString"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="261" startColumn="13" endLine="261" endColumn="59" document="1"/> <entry offset="0x1" startLine="262" startColumn="17" endLine="262" endColumn="39" document="1"/> <entry offset="0xa" startLine="263" startColumn="13" endLine="263" endColumn="25" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0xc"> <importsforward declaringType="My.MyProject+MyWebServices" methodName="Equals" parameterNames="o"/> <local name="ToString" il_index="0" il_start="0x0" il_end="0xc" attributes="0"/> </scope> </method> <method containingType="My.MyProject+MyWebServices" name="Create__Instance__" parameterNames="instance"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> <slot kind="1" offset="0"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="266" startColumn="12" endLine="266" endColumn="95" document="1"/> <entry offset="0x1" startLine="267" startColumn="17" endLine="267" endColumn="44" document="1"/> <entry offset="0xb" hidden="true" document="1"/> <entry offset="0xe" startLine="268" startColumn="21" endLine="268" endColumn="35" document="1"/> <entry offset="0x16" startLine="269" startColumn="17" endLine="269" endColumn="21" document="1"/> <entry offset="0x17" startLine="270" startColumn="21" endLine="270" endColumn="36" document="1"/> <entry offset="0x1b" startLine="272" startColumn="13" endLine="272" endColumn="25" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x1d"> <importsforward declaringType="My.MyProject+MyWebServices" methodName="Equals" parameterNames="o"/> <local name="Create__Instance__" il_index="0" il_start="0x0" il_end="0x1d" attributes="0"/> </scope> </method> <method containingType="My.MyProject+MyWebServices" name="Dispose__Instance__" parameterNames="instance"> <sequencePoints> <entry offset="0x0" startLine="275" startColumn="13" endLine="275" endColumn="71" document="1"/> <entry offset="0x1" startLine="276" startColumn="17" endLine="276" endColumn="35" document="1"/> <entry offset="0x8" startLine="277" startColumn="13" endLine="277" endColumn="20" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x9"> <importsforward declaringType="My.MyProject+MyWebServices" methodName="Equals" parameterNames="o"/> </scope> </method> <method containingType="My.MyProject+MyWebServices" name=".ctor"> <sequencePoints> <entry offset="0x0" startLine="281" startColumn="13" endLine="281" endColumn="29" document="1"/> <entry offset="0x1" startLine="282" startColumn="16" endLine="282" endColumn="28" document="1"/> <entry offset="0x8" startLine="283" startColumn="13" endLine="283" endColumn="20" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x9"> <importsforward declaringType="My.MyProject+MyWebServices" methodName="Equals" parameterNames="o"/> </scope> </method> <method containingType="My.MyProject+ThreadSafeObjectProvider`1" name="get_GetInstance"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> <slot kind="1" offset="0"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="343" startColumn="17" endLine="343" endColumn="20" document="1"/> <entry offset="0x1" startLine="344" startColumn="21" endLine="344" endColumn="59" document="1"/> <entry offset="0xf" hidden="true" document="1"/> <entry offset="0x12" startLine="344" startColumn="60" endLine="344" endColumn="87" document="1"/> <entry offset="0x1c" startLine="345" startColumn="21" endLine="345" endColumn="47" document="1"/> <entry offset="0x24" startLine="346" startColumn="17" endLine="346" endColumn="24" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x26"> <importsforward declaringType="My.MyProject+MyWebServices" methodName="Equals" parameterNames="o"/> <local name="GetInstance" il_index="0" il_start="0x0" il_end="0x26" attributes="0"/> </scope> </method> <method containingType="My.MyProject+ThreadSafeObjectProvider`1" name=".ctor"> <sequencePoints> <entry offset="0x0" startLine="352" startColumn="13" endLine="352" endColumn="29" document="1"/> <entry offset="0x1" startLine="353" startColumn="17" endLine="353" endColumn="29" document="1"/> <entry offset="0x8" startLine="354" startColumn="13" endLine="354" endColumn="20" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x9"> <importsforward declaringType="My.MyProject+MyWebServices" methodName="Equals" parameterNames="o"/> </scope> </method> </methods> </symbols>, options:=PdbValidationOptions.SkipConversionValidation) ' TODO: https://github.com/dotnet/roslyn/issues/18004 End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub ConstructorsWithoutInitializers() Dim source = <compilation> <file><![CDATA[ Class C Sub New() Dim o As Object End Sub Sub New(x As Object) Dim y As Object = x End Sub End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) compilation.VerifyPdb("C..ctor", <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="C" name=".ctor"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="2" startColumn="5" endLine="2" endColumn="14" document="1"/> <entry offset="0x8" startLine="4" startColumn="5" endLine="4" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x9"> <currentnamespace name=""/> <local name="o" il_index="0" il_start="0x0" il_end="0x9" attributes="0"/> </scope> </method> <method containingType="C" name=".ctor" parameterNames="x"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="5" startColumn="5" endLine="5" endColumn="25" document="1"/> <entry offset="0x8" startLine="6" startColumn="13" endLine="6" endColumn="28" document="1"/> <entry offset="0xf" startLine="7" startColumn="5" endLine="7" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x10"> <importsforward declaringType="C" methodName=".ctor"/> <local name="y" il_index="0" il_start="0x0" il_end="0x10" attributes="0"/> </scope> </method> </methods> </symbols>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub ConstructorsWithInitializers() Dim source = <compilation> <file><![CDATA[ Class C Shared G As Object = 1 Private F As Object = G Sub New() Dim o As Object End Sub Sub New(x As Object) Dim y As Object = x End Sub End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) compilation.VerifyPdb("C..ctor", <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="C" name=".ctor"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="4" startColumn="5" endLine="4" endColumn="14" document="1"/> <entry offset="0x8" startLine="3" startColumn="13" endLine="3" endColumn="28" document="1"/> <entry offset="0x18" startLine="6" startColumn="5" endLine="6" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x19"> <importsforward declaringType="C" methodName=".cctor"/> <local name="o" il_index="0" il_start="0x0" il_end="0x19" attributes="0"/> </scope> </method> <method containingType="C" name=".ctor" parameterNames="x"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="7" startColumn="5" endLine="7" endColumn="25" document="1"/> <entry offset="0x8" startLine="3" startColumn="13" endLine="3" endColumn="28" document="1"/> <entry offset="0x18" startLine="8" startColumn="13" endLine="8" endColumn="28" document="1"/> <entry offset="0x1f" startLine="9" startColumn="5" endLine="9" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x20"> <importsforward declaringType="C" methodName=".cctor"/> <local name="y" il_index="0" il_start="0x0" il_end="0x20" attributes="0"/> </scope> </method> </methods> </symbols>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub TryCatchFinally() Dim source = <compilation> <file><![CDATA[ Option Strict On Imports System Module M1 Public Sub Main() Dim x As Integer = 0 Try Dim y As String = "y" label1: label2: If x = 0 Then Throw New Exception() End If Catch ex As Exception Dim z As String = "z" Console.WriteLine(x) x = 1 GoTo label1 Finally Dim q As String = "q" Console.WriteLine(x) End Try Console.WriteLine(x) End Sub End Module ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe) compilation.VerifyPdb("M1.Main", <symbols> <files> <file id="1" name="" language="VB"/> </files> <entryPoint declaringType="M1" methodName="Main"/> <methods> <method containingType="M1" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> <slot kind="0" offset="51"/> <slot kind="1" offset="100"/> <slot kind="0" offset="182"/> <slot kind="0" offset="221"/> <slot kind="0" offset="351"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="5" startColumn="5" endLine="5" endColumn="22" document="1"/> <entry offset="0x1" startLine="6" startColumn="13" endLine="6" endColumn="29" document="1"/> <entry offset="0x3" startLine="7" startColumn="9" endLine="7" endColumn="12" document="1"/> <entry offset="0x4" startLine="8" startColumn="17" endLine="8" endColumn="34" document="1"/> <entry offset="0xa" startLine="9" startColumn="1" endLine="9" endColumn="8" document="1"/> <entry offset="0xb" startLine="10" startColumn="1" endLine="10" endColumn="8" document="1"/> <entry offset="0xc" startLine="11" startColumn="13" endLine="11" endColumn="26" document="1"/> <entry offset="0x11" hidden="true" document="1"/> <entry offset="0x14" startLine="12" startColumn="17" endLine="12" endColumn="38" document="1"/> <entry offset="0x1a" startLine="13" startColumn="13" endLine="13" endColumn="19" document="1"/> <entry offset="0x1d" hidden="true" document="1"/> <entry offset="0x24" startLine="14" startColumn="9" endLine="14" endColumn="30" document="1"/> <entry offset="0x25" startLine="15" startColumn="17" endLine="15" endColumn="34" document="1"/> <entry offset="0x2c" startLine="16" startColumn="13" endLine="16" endColumn="33" document="1"/> <entry offset="0x33" startLine="17" startColumn="13" endLine="17" endColumn="18" document="1"/> <entry offset="0x35" startLine="18" startColumn="13" endLine="18" endColumn="24" document="1"/> <entry offset="0x3c" hidden="true" document="1"/> <entry offset="0x3e" startLine="19" startColumn="9" endLine="19" endColumn="16" document="1"/> <entry offset="0x3f" startLine="20" startColumn="17" endLine="20" endColumn="34" document="1"/> <entry offset="0x46" startLine="21" startColumn="13" endLine="21" endColumn="33" document="1"/> <entry offset="0x4e" startLine="22" startColumn="9" endLine="22" endColumn="16" document="1"/> <entry offset="0x4f" startLine="24" startColumn="9" endLine="24" endColumn="29" document="1"/> <entry offset="0x56" startLine="26" startColumn="5" endLine="26" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x57"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> <local name="x" il_index="0" il_start="0x0" il_end="0x57" attributes="0"/> <scope startOffset="0x4" endOffset="0x1a"> <local name="y" il_index="1" il_start="0x4" il_end="0x1a" attributes="0"/> </scope> <scope startOffset="0x1d" endOffset="0x3b"> <local name="ex" il_index="3" il_start="0x1d" il_end="0x3b" attributes="0"/> <scope startOffset="0x25" endOffset="0x3b"> <local name="z" il_index="4" il_start="0x25" il_end="0x3b" attributes="0"/> </scope> </scope> <scope startOffset="0x3f" endOffset="0x4c"> <local name="q" il_index="5" il_start="0x3f" il_end="0x4c" attributes="0"/> </scope> </scope> </method> </methods> </symbols>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub TryCatchWhen_Debug() Dim source = <compilation> <file> Option Strict On Imports System Module M1 Public Sub Main() Dim x As Integer = 0 Try Dim y As String = "y" label1: label2: x = x \ x Catch ex As Exception When ex.Message IsNot Nothing Dim z As String = "z" Console.WriteLine(x) x = 1 GoTo label1 Finally Dim q As String = "q" Console.WriteLine(x) End Try Console.WriteLine(x) End Sub End Module </file> </compilation> Dim v = CompileAndVerify(CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe)) v.VerifyIL("M1.Main", " { // Code size 104 (0x68) .maxstack 2 .locals init (Integer V_0, //x String V_1, //y System.Exception V_2, //ex Boolean V_3, String V_4, //z String V_5) //q -IL_0000: nop -IL_0001: ldc.i4.0 IL_0002: stloc.0 .try { .try { -IL_0003: nop -IL_0004: ldstr ""y"" IL_0009: stloc.1 -IL_000a: nop -IL_000b: nop -IL_000c: ldloc.0 IL_000d: ldloc.0 IL_000e: div IL_000f: stloc.0 IL_0010: leave.s IL_004d } filter { ~IL_0012: isinst ""System.Exception"" IL_0017: dup IL_0018: brtrue.s IL_001e IL_001a: pop IL_001b: ldc.i4.0 IL_001c: br.s IL_0033 IL_001e: dup IL_001f: call ""Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)"" IL_0024: stloc.2 -IL_0025: ldloc.2 IL_0026: callvirt ""Function System.Exception.get_Message() As String"" IL_002b: ldnull IL_002c: cgt.un IL_002e: stloc.3 ~IL_002f: ldloc.3 IL_0030: ldc.i4.0 IL_0031: cgt.un IL_0033: endfilter } // end filter { // handler ~IL_0035: pop -IL_0036: ldstr ""z"" IL_003b: stloc.s V_4 -IL_003d: ldloc.0 IL_003e: call ""Sub System.Console.WriteLine(Integer)"" IL_0043: nop -IL_0044: ldc.i4.1 IL_0045: stloc.0 -IL_0046: call ""Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()"" IL_004b: leave.s IL_000a } ~IL_004d: leave.s IL_005f } finally { -IL_004f: nop -IL_0050: ldstr ""q"" IL_0055: stloc.s V_5 -IL_0057: ldloc.0 IL_0058: call ""Sub System.Console.WriteLine(Integer)"" IL_005d: nop IL_005e: endfinally } -IL_005f: nop -IL_0060: ldloc.0 IL_0061: call ""Sub System.Console.WriteLine(Integer)"" IL_0066: nop -IL_0067: ret } ", sequencePoints:="M1.Main") v.VerifyPdb("M1.Main", <symbols> <files> <file id="1" name="" language="VB"/> </files> <entryPoint declaringType="M1" methodName="Main"/> <methods> <method containingType="M1" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> <slot kind="0" offset="51"/> <slot kind="0" offset="119"/> <slot kind="1" offset="141"/> <slot kind="0" offset="188"/> <slot kind="0" offset="318"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="5" startColumn="5" endLine="5" endColumn="22" document="1"/> <entry offset="0x1" startLine="6" startColumn="13" endLine="6" endColumn="29" document="1"/> <entry offset="0x3" startLine="7" startColumn="9" endLine="7" endColumn="12" document="1"/> <entry offset="0x4" startLine="8" startColumn="17" endLine="8" endColumn="34" document="1"/> <entry offset="0xa" startLine="9" startColumn="1" endLine="9" endColumn="8" document="1"/> <entry offset="0xb" startLine="10" startColumn="1" endLine="10" endColumn="8" document="1"/> <entry offset="0xc" startLine="11" startColumn="13" endLine="11" endColumn="22" document="1"/> <entry offset="0x12" hidden="true" document="1"/> <entry offset="0x25" startLine="12" startColumn="9" endLine="12" endColumn="60" document="1"/> <entry offset="0x2f" hidden="true" document="1"/> <entry offset="0x35" hidden="true" document="1"/> <entry offset="0x36" startLine="13" startColumn="17" endLine="13" endColumn="34" document="1"/> <entry offset="0x3d" startLine="14" startColumn="13" endLine="14" endColumn="33" document="1"/> <entry offset="0x44" startLine="15" startColumn="13" endLine="15" endColumn="18" document="1"/> <entry offset="0x46" startLine="16" startColumn="13" endLine="16" endColumn="24" document="1"/> <entry offset="0x4d" hidden="true" document="1"/> <entry offset="0x4f" startLine="17" startColumn="9" endLine="17" endColumn="16" document="1"/> <entry offset="0x50" startLine="18" startColumn="17" endLine="18" endColumn="34" document="1"/> <entry offset="0x57" startLine="19" startColumn="13" endLine="19" endColumn="33" document="1"/> <entry offset="0x5f" startLine="20" startColumn="9" endLine="20" endColumn="16" document="1"/> <entry offset="0x60" startLine="22" startColumn="9" endLine="22" endColumn="29" document="1"/> <entry offset="0x67" startLine="24" startColumn="5" endLine="24" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x68"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> <local name="x" il_index="0" il_start="0x0" il_end="0x68" attributes="0"/> <scope startOffset="0x4" endOffset="0xf"> <local name="y" il_index="1" il_start="0x4" il_end="0xf" attributes="0"/> </scope> <scope startOffset="0x12" endOffset="0x4c"> <local name="ex" il_index="2" il_start="0x12" il_end="0x4c" attributes="0"/> <scope startOffset="0x36" endOffset="0x4c"> <local name="z" il_index="4" il_start="0x36" il_end="0x4c" attributes="0"/> </scope> </scope> <scope startOffset="0x50" endOffset="0x5d"> <local name="q" il_index="5" il_start="0x50" il_end="0x5d" attributes="0"/> </scope> </scope> </method> </methods> </symbols>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub TryCatchWhen_Release() Dim source = <compilation> <file> Imports System Imports System.IO Module M1 Function filter(e As Exception) Return True End Function Public Sub Main() Try Throw New InvalidOperationException() Catch e As IOException When filter(e) Console.WriteLine() Catch e As Exception When filter(e) Console.WriteLine() End Try End Sub End Module </file> </compilation> Dim v = CompileAndVerify(CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe)) v.VerifyIL("M1.Main", " { // Code size 103 (0x67) .maxstack 2 .locals init (System.IO.IOException V_0, //e System.Exception V_1) //e .try { -IL_0000: newobj ""Sub System.InvalidOperationException..ctor()"" IL_0005: throw } filter { ~IL_0006: isinst ""System.IO.IOException"" IL_000b: dup IL_000c: brtrue.s IL_0012 IL_000e: pop IL_000f: ldc.i4.0 IL_0010: br.s IL_0027 IL_0012: dup IL_0013: call ""Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)"" IL_0018: stloc.0 -IL_0019: ldloc.0 IL_001a: call ""Function M1.filter(System.Exception) As Object"" IL_001f: call ""Function Microsoft.VisualBasic.CompilerServices.Conversions.ToBoolean(Object) As Boolean"" IL_0024: ldc.i4.0 IL_0025: cgt.un IL_0027: endfilter } // end filter { // handler ~IL_0029: pop -IL_002a: call ""Sub System.Console.WriteLine()"" IL_002f: call ""Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()"" IL_0034: leave.s IL_0066 } filter { ~IL_0036: isinst ""System.Exception"" IL_003b: dup IL_003c: brtrue.s IL_0042 IL_003e: pop IL_003f: ldc.i4.0 IL_0040: br.s IL_0057 IL_0042: dup IL_0043: call ""Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)"" IL_0048: stloc.1 -IL_0049: ldloc.1 IL_004a: call ""Function M1.filter(System.Exception) As Object"" IL_004f: call ""Function Microsoft.VisualBasic.CompilerServices.Conversions.ToBoolean(Object) As Boolean"" IL_0054: ldc.i4.0 IL_0055: cgt.un IL_0057: endfilter } // end filter { // handler ~IL_0059: pop -IL_005a: call ""Sub System.Console.WriteLine()"" IL_005f: call ""Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()"" IL_0064: leave.s IL_0066 } -IL_0066: ret } ", sequencePoints:="M1.Main") End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub TestBasic1() Dim source = <compilation> <file><![CDATA[ Option Strict On Module Module1 Sub Main() Dim x As Integer = 3 Do While (x <= 3) Dim y As Integer = x + 1 x = y Loop End Sub End Module ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( source, TestOptions.DebugExe) compilation.VerifyPdb("Module1.Main", <symbols> <files> <file id="1" name="" language="VB"/> </files> <entryPoint declaringType="Module1" methodName="Main"/> <methods> <method containingType="Module1" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> <slot kind="0" offset="65"/> <slot kind="1" offset="30"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="4" startColumn="5" endLine="4" endColumn="15" document="1"/> <entry offset="0x1" startLine="5" startColumn="13" endLine="5" endColumn="29" document="1"/> <entry offset="0x3" hidden="true" document="1"/> <entry offset="0x5" startLine="7" startColumn="17" endLine="7" endColumn="37" document="1"/> <entry offset="0x9" startLine="8" startColumn="13" endLine="8" endColumn="18" document="1"/> <entry offset="0xb" startLine="9" startColumn="9" endLine="9" endColumn="13" document="1"/> <entry offset="0xc" startLine="6" startColumn="9" endLine="6" endColumn="26" document="1"/> <entry offset="0x14" hidden="true" document="1"/> <entry offset="0x17" startLine="10" startColumn="5" endLine="10" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x18"> <currentnamespace name=""/> <local name="x" il_index="0" il_start="0x0" il_end="0x18" attributes="0"/> <scope startOffset="0x5" endOffset="0xb"> <local name="y" il_index="1" il_start="0x5" il_end="0xb" attributes="0"/> </scope> </scope> </method> </methods> </symbols>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub TestBasicCtor() Dim source = <compilation> <file><![CDATA[ Class C1 Sub New() System.Console.WriteLine("Hello, world.") End Sub End Class ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugDll) compilation.VerifyPdb("C1..ctor", <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="C1" name=".ctor"> <sequencePoints> <entry offset="0x0" startLine="2" startColumn="5" endLine="2" endColumn="14" document="1"/> <entry offset="0x8" startLine="3" startColumn="9" endLine="3" endColumn="50" document="1"/> <entry offset="0x13" startLine="4" startColumn="5" endLine="4" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x14"> <currentnamespace name=""/> </scope> </method> </methods> </symbols>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub TestLabels() Dim source = <compilation> <file><![CDATA[ Class C1 Sub New() label1: label2: label3: goto label2: End Sub End Class ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugDll) compilation.VerifyPdb("C1..ctor", <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="C1" name=".ctor"> <sequencePoints> <entry offset="0x0" startLine="2" startColumn="5" endLine="2" endColumn="14" document="1"/> <entry offset="0x8" startLine="3" startColumn="9" endLine="3" endColumn="16" document="1"/> <entry offset="0x9" startLine="4" startColumn="9" endLine="4" endColumn="16" document="1"/> <entry offset="0xa" startLine="5" startColumn="9" endLine="5" endColumn="16" document="1"/> <entry offset="0xb" startLine="7" startColumn="9" endLine="7" endColumn="20" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0xd"> <currentnamespace name=""/> </scope> </method> </methods> </symbols>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub IfStatement() Dim source = <compilation> <file><![CDATA[ Imports System Class C Sub F() If G() Then Console.WriteLine(1) Else Console.WriteLine(2) End If Console.WriteLine(3) End Sub Function G() As Boolean Return False End Function End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugDll) Dim v = CompileAndVerify(compilation) v.VerifyIL("C.F", " { // Code size 38 (0x26) .maxstack 1 .locals init (Boolean V_0) -IL_0000: nop -IL_0001: ldarg.0 IL_0002: call ""Function C.G() As Boolean"" IL_0007: stloc.0 ~IL_0008: ldloc.0 IL_0009: brfalse.s IL_0015 -IL_000b: ldc.i4.1 IL_000c: call ""Sub System.Console.WriteLine(Integer)"" IL_0011: nop -IL_0012: nop IL_0013: br.s IL_001e -IL_0015: nop -IL_0016: ldc.i4.2 IL_0017: call ""Sub System.Console.WriteLine(Integer)"" IL_001c: nop -IL_001d: nop -IL_001e: ldc.i4.3 IL_001f: call ""Sub System.Console.WriteLine(Integer)"" IL_0024: nop -IL_0025: ret } ", sequencePoints:="C.F") v.VerifyPdb("C.F", <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="C" name="F"> <customDebugInfo> <encLocalSlotMap> <slot kind="1" offset="0"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="4" startColumn="5" endLine="4" endColumn="12" document="1"/> <entry offset="0x1" startLine="5" startColumn="9" endLine="5" endColumn="20" document="1"/> <entry offset="0x8" hidden="true" document="1"/> <entry offset="0xb" startLine="6" startColumn="13" endLine="6" endColumn="33" document="1"/> <entry offset="0x12" startLine="9" startColumn="9" endLine="9" endColumn="15" document="1"/> <entry offset="0x15" startLine="7" startColumn="9" endLine="7" endColumn="13" document="1"/> <entry offset="0x16" startLine="8" startColumn="13" endLine="8" endColumn="33" document="1"/> <entry offset="0x1d" startLine="9" startColumn="9" endLine="9" endColumn="15" document="1"/> <entry offset="0x1e" startLine="11" startColumn="9" endLine="11" endColumn="29" document="1"/> <entry offset="0x25" startLine="12" startColumn="5" endLine="12" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x26"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> </scope> </method> </methods> </symbols>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub DoWhileStatement() Dim source = <compilation> <file><![CDATA[ Imports System Class C Sub F() Do While G() Console.WriteLine(1) Loop End Sub Function G() As Boolean Return False End Function End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugDll) Dim v = CompileAndVerify(compilation) v.VerifyIL("C.F", " { // Code size 22 (0x16) .maxstack 1 .locals init (Boolean V_0) -IL_0000: nop ~IL_0001: br.s IL_000b -IL_0003: ldc.i4.1 IL_0004: call ""Sub System.Console.WriteLine(Integer)"" IL_0009: nop -IL_000a: nop -IL_000b: ldarg.0 IL_000c: call ""Function C.G() As Boolean"" IL_0011: stloc.0 ~IL_0012: ldloc.0 IL_0013: brtrue.s IL_0003 -IL_0015: ret } ", sequencePoints:="C.F") v.VerifyPdb("C.F", <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="C" name="F"> <customDebugInfo> <encLocalSlotMap> <slot kind="1" offset="0"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="4" startColumn="5" endLine="4" endColumn="12" document="1"/> <entry offset="0x1" hidden="true" document="1"/> <entry offset="0x3" startLine="6" startColumn="13" endLine="6" endColumn="33" document="1"/> <entry offset="0xa" startLine="7" startColumn="9" endLine="7" endColumn="13" document="1"/> <entry offset="0xb" startLine="5" startColumn="9" endLine="5" endColumn="21" document="1"/> <entry offset="0x12" hidden="true" document="1"/> <entry offset="0x15" startLine="8" startColumn="5" endLine="8" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x16"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> </scope> </method> </methods> </symbols>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub DoLoopWhileStatement() Dim source = <compilation> <file><![CDATA[ Imports System Class C Sub F() Do Console.WriteLine(1) Loop While G() End Sub Function G() As Boolean Return False End Function End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugDll) Dim v = CompileAndVerify(compilation) v.VerifyIL("C.F", " { // Code size 21 (0x15) .maxstack 1 .locals init (Boolean V_0) -IL_0000: nop -IL_0001: nop -IL_0002: ldc.i4.1 IL_0003: call ""Sub System.Console.WriteLine(Integer)"" IL_0008: nop -IL_0009: nop IL_000a: ldarg.0 IL_000b: call ""Function C.G() As Boolean"" IL_0010: stloc.0 ~IL_0011: ldloc.0 IL_0012: brtrue.s IL_0001 -IL_0014: ret } ", sequencePoints:="C.F") v.VerifyPdb("C.F", <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="C" name="F"> <customDebugInfo> <encLocalSlotMap> <slot kind="1" offset="0"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="4" startColumn="5" endLine="4" endColumn="12" document="1"/> <entry offset="0x1" startLine="5" startColumn="9" endLine="5" endColumn="11" document="1"/> <entry offset="0x2" startLine="6" startColumn="13" endLine="6" endColumn="33" document="1"/> <entry offset="0x9" startLine="7" startColumn="9" endLine="7" endColumn="23" document="1"/> <entry offset="0x11" hidden="true" document="1"/> <entry offset="0x14" startLine="8" startColumn="5" endLine="8" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x15"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> </scope> </method> </methods> </symbols>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub ForStatement() Dim source = <compilation> <file><![CDATA[ Imports System Class C Sub F() For a = G(0) To G(1) Step G(2) Console.WriteLine(1) Next End Sub Function G(a As Integer) As Integer Return 10 End Function End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugDll) Dim v = CompileAndVerify(compilation) v.VerifyIL("C.F", " { // Code size 55 (0x37) .maxstack 3 .locals init (Integer V_0, Integer V_1, Integer V_2, Integer V_3) //a -IL_0000: nop -IL_0001: ldarg.0 IL_0002: ldc.i4.0 IL_0003: call ""Function C.G(Integer) As Integer"" IL_0008: stloc.0 IL_0009: ldarg.0 IL_000a: ldc.i4.1 IL_000b: call ""Function C.G(Integer) As Integer"" IL_0010: stloc.1 IL_0011: ldarg.0 IL_0012: ldc.i4.2 IL_0013: call ""Function C.G(Integer) As Integer"" IL_0018: stloc.2 IL_0019: ldloc.0 IL_001a: stloc.3 ~IL_001b: br.s IL_0028 -IL_001d: ldc.i4.1 IL_001e: call ""Sub System.Console.WriteLine(Integer)"" IL_0023: nop -IL_0024: ldloc.3 IL_0025: ldloc.2 IL_0026: add.ovf IL_0027: stloc.3 ~IL_0028: ldloc.2 IL_0029: ldc.i4.s 31 IL_002b: shr IL_002c: ldloc.3 IL_002d: xor IL_002e: ldloc.2 IL_002f: ldc.i4.s 31 IL_0031: shr IL_0032: ldloc.1 IL_0033: xor IL_0034: ble.s IL_001d -IL_0036: ret }", sequencePoints:="C.F") v.VerifyPdb("C.F", <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="C" name="F"> <customDebugInfo> <encLocalSlotMap> <slot kind="13" offset="0"/> <slot kind="11" offset="0"/> <slot kind="12" offset="0"/> <slot kind="0" offset="0"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="4" startColumn="5" endLine="4" endColumn="12" document="1"/> <entry offset="0x1" startLine="5" startColumn="9" endLine="5" endColumn="39" document="1"/> <entry offset="0x1b" hidden="true" document="1"/> <entry offset="0x1d" startLine="6" startColumn="13" endLine="6" endColumn="33" document="1"/> <entry offset="0x24" startLine="7" startColumn="9" endLine="7" endColumn="13" document="1"/> <entry offset="0x28" hidden="true" document="1"/> <entry offset="0x36" startLine="8" startColumn="5" endLine="8" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x37"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> <scope startOffset="0x1" endOffset="0x35"> <local name="a" il_index="3" il_start="0x1" il_end="0x35" attributes="0"/> </scope> </scope> </method> </methods> </symbols>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub ForStatement_LateBound() Dim v = CompileAndVerify( <compilation> <file name="a.vb"> Option Strict On Public Class MyClass1 Public Shared Sub Main() Dim ctrlVar As Object Dim initValue As Object = 0 Dim limit As Object = 2 Dim stp As Object = 1 For ctrlVar = initValue To limit Step stp System.Console.WriteLine(ctrlVar) Next End Sub End Class </file> </compilation>, options:=TestOptions.DebugDll) v.VerifyIL("MyClass1.Main", " { // Code size 70 (0x46) .maxstack 6 .locals init (Object V_0, //ctrlVar Object V_1, //initValue Object V_2, //limit Object V_3, //stp Object V_4, Boolean V_5, Boolean V_6) -IL_0000: nop -IL_0001: ldc.i4.0 IL_0002: box ""Integer"" IL_0007: stloc.1 -IL_0008: ldc.i4.2 IL_0009: box ""Integer"" IL_000e: stloc.2 -IL_000f: ldc.i4.1 IL_0010: box ""Integer"" IL_0015: stloc.3 -IL_0016: ldloc.0 IL_0017: ldloc.1 IL_0018: ldloc.2 IL_0019: ldloc.3 IL_001a: ldloca.s V_4 IL_001c: ldloca.s V_0 IL_001e: call ""Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForLoopInitObj(Object, Object, Object, Object, ByRef Object, ByRef Object) As Boolean"" IL_0023: stloc.s V_5 ~IL_0025: ldloc.s V_5 IL_0027: brfalse.s IL_0045 -IL_0029: ldloc.0 IL_002a: call ""Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"" IL_002f: call ""Sub System.Console.WriteLine(Object)"" IL_0034: nop -IL_0035: ldloc.0 IL_0036: ldloc.s V_4 IL_0038: ldloca.s V_0 IL_003a: call ""Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForNextCheckObj(Object, Object, ByRef Object) As Boolean"" IL_003f: stloc.s V_6 ~IL_0041: ldloc.s V_6 IL_0043: brtrue.s IL_0029 -IL_0045: ret } ", sequencePoints:="MyClass1.Main") v.VerifyPdb("MyClass1.Main", <symbols> <files> <file id="1" name="a.vb" language="VB" checksumAlgorithm="SHA1" checksum="87-56-72-A9-63-E5-5D-0C-F3-97-85-44-CF-51-55-8E-76-E7-1D-F1"/> </files> <methods> <method containingType="MyClass1" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> <slot kind="0" offset="35"/> <slot kind="0" offset="72"/> <slot kind="0" offset="105"/> <slot kind="13" offset="134"/> <slot kind="1" offset="134"/> <slot kind="1" offset="134" ordinal="1"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="3" startColumn="5" endLine="3" endColumn="29" document="1"/> <entry offset="0x1" startLine="6" startColumn="13" endLine="6" endColumn="36" document="1"/> <entry offset="0x8" startLine="7" startColumn="13" endLine="7" endColumn="32" document="1"/> <entry offset="0xf" startLine="8" startColumn="13" endLine="8" endColumn="30" document="1"/> <entry offset="0x16" startLine="10" startColumn="9" endLine="10" endColumn="50" document="1"/> <entry offset="0x25" hidden="true" document="1"/> <entry offset="0x29" startLine="11" startColumn="13" endLine="11" endColumn="46" document="1"/> <entry offset="0x35" startLine="12" startColumn="9" endLine="12" endColumn="13" document="1"/> <entry offset="0x41" hidden="true" document="1"/> <entry offset="0x45" startLine="14" startColumn="5" endLine="14" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x46"> <currentnamespace name=""/> <local name="ctrlVar" il_index="0" il_start="0x0" il_end="0x46" attributes="0"/> <local name="initValue" il_index="1" il_start="0x0" il_end="0x46" attributes="0"/> <local name="limit" il_index="2" il_start="0x0" il_end="0x46" attributes="0"/> <local name="stp" il_index="3" il_start="0x0" il_end="0x46" attributes="0"/> </scope> </method> </methods> </symbols>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub SelectCaseStatement() Dim source = <compilation> <file><![CDATA[ Imports System Class C Sub F() Select Case G(1) Case G(2) Console.WriteLine(4) Case G(3) Console.WriteLine(5) End Select End Sub Function G(a As Integer) As Integer Return a End Function End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugDll) Dim v = CompileAndVerify(compilation) v.VerifyIL("C.F", " { // Code size 56 (0x38) .maxstack 3 .locals init (Integer V_0, Boolean V_1) -IL_0000: nop -IL_0001: nop IL_0002: ldarg.0 IL_0003: ldc.i4.1 IL_0004: call ""Function C.G(Integer) As Integer"" IL_0009: stloc.0 -IL_000a: ldloc.0 IL_000b: ldarg.0 IL_000c: ldc.i4.2 IL_000d: call ""Function C.G(Integer) As Integer"" IL_0012: ceq IL_0014: stloc.1 ~IL_0015: ldloc.1 IL_0016: brfalse.s IL_0021 -IL_0018: ldc.i4.4 IL_0019: call ""Sub System.Console.WriteLine(Integer)"" IL_001e: nop IL_001f: br.s IL_0036 -IL_0021: ldloc.0 IL_0022: ldarg.0 IL_0023: ldc.i4.3 IL_0024: call ""Function C.G(Integer) As Integer"" IL_0029: ceq IL_002b: stloc.1 ~IL_002c: ldloc.1 IL_002d: brfalse.s IL_0036 -IL_002f: ldc.i4.5 IL_0030: call ""Sub System.Console.WriteLine(Integer)"" IL_0035: nop -IL_0036: nop -IL_0037: ret } ", sequencePoints:="C.F") v.VerifyPdb("C.F", <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="C" name="F"> <customDebugInfo> <encLocalSlotMap> <slot kind="15" offset="0"/> <slot kind="1" offset="0"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="4" startColumn="5" endLine="4" endColumn="12" document="1"/> <entry offset="0x1" startLine="5" startColumn="9" endLine="5" endColumn="25" document="1"/> <entry offset="0xa" startLine="6" startColumn="13" endLine="6" endColumn="22" document="1"/> <entry offset="0x15" hidden="true" document="1"/> <entry offset="0x18" startLine="7" startColumn="17" endLine="7" endColumn="37" document="1"/> <entry offset="0x21" startLine="8" startColumn="13" endLine="8" endColumn="22" document="1"/> <entry offset="0x2c" hidden="true" document="1"/> <entry offset="0x2f" startLine="9" startColumn="17" endLine="9" endColumn="37" document="1"/> <entry offset="0x36" startLine="10" startColumn="9" endLine="10" endColumn="19" document="1"/> <entry offset="0x37" startLine="11" startColumn="5" endLine="11" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x38"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> </scope> </method> </methods> </symbols>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub TestIfThenAndBlocks() Dim source = <compilation> <file><![CDATA[ Imports System Module Module1 Sub Main(args As String()) Dim x As Integer = 0, xx = New Integer() If x < 10 Then Dim s As String = "hi" : Console.WriteLine(s) Else Console.WriteLine("bye") : Console.WriteLine("bye1") If x > 10 Then Console.WriteLine("hi") : Console.WriteLine("hi1") Else Dim s As String = "bye" : Console.WriteLine(s) Do While x < 5 If x < 1 Then Console.WriteLine("<1") ElseIf x < 2 Then Dim s2 As String = "<2" Console.WriteLine(s2) ElseIf x < 3 Then Dim s3 As String = "<3" Console.WriteLine(s3) Else Dim e1 As String = "Else" Console.WriteLine(e1) End If Dim newX As Integer = x + 1 x = newX Loop End Sub End Module ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe) compilation.VerifyPdb("Module1.Main", <symbols> <files> <file id="1" name="" language="VB"/> </files> <entryPoint declaringType="Module1" methodName="Main" parameterNames="args"/> <methods> <method containingType="Module1" name="Main" parameterNames="args"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> <slot kind="0" offset="22"/> <slot kind="1" offset="52"/> <slot kind="0" offset="71"/> <slot kind="1" offset="180"/> <slot kind="0" offset="255"/> <slot kind="0" offset="753"/> <slot kind="1" offset="337"/> <slot kind="1" offset="405"/> <slot kind="0" offset="444"/> <slot kind="1" offset="516"/> <slot kind="0" offset="555"/> <slot kind="0" offset="653"/> <slot kind="1" offset="309"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="4" startColumn="5" endLine="4" endColumn="31" document="1"/> <entry offset="0x1" startLine="6" startColumn="13" endLine="6" endColumn="29" document="1"/> <entry offset="0x3" startLine="6" startColumn="31" endLine="6" endColumn="49" document="1"/> <entry offset="0xb" startLine="8" startColumn="9" endLine="8" endColumn="23" document="1"/> <entry offset="0x11" hidden="true" document="1"/> <entry offset="0x14" startLine="8" startColumn="28" endLine="8" endColumn="46" document="1"/> <entry offset="0x1a" startLine="8" startColumn="49" endLine="8" endColumn="69" document="1"/> <entry offset="0x23" startLine="8" startColumn="70" endLine="8" endColumn="74" document="1"/> <entry offset="0x24" startLine="8" startColumn="75" endLine="8" endColumn="99" document="1"/> <entry offset="0x2f" startLine="8" startColumn="102" endLine="8" endColumn="127" document="1"/> <entry offset="0x3a" startLine="9" startColumn="9" endLine="9" endColumn="23" document="1"/> <entry offset="0x41" hidden="true" document="1"/> <entry offset="0x45" startLine="9" startColumn="24" endLine="9" endColumn="47" document="1"/> <entry offset="0x50" startLine="9" startColumn="50" endLine="9" endColumn="74" document="1"/> <entry offset="0x5d" startLine="9" startColumn="75" endLine="9" endColumn="79" document="1"/> <entry offset="0x5e" startLine="9" startColumn="84" endLine="9" endColumn="103" document="1"/> <entry offset="0x65" startLine="9" startColumn="106" endLine="9" endColumn="126" document="1"/> <entry offset="0x6d" hidden="true" document="1"/> <entry offset="0x6f" startLine="12" startColumn="13" endLine="12" endColumn="26" document="1"/> <entry offset="0x75" hidden="true" document="1"/> <entry offset="0x79" startLine="13" startColumn="17" endLine="13" endColumn="40" document="1"/> <entry offset="0x84" startLine="23" startColumn="13" endLine="23" endColumn="19" document="1"/> <entry offset="0x87" startLine="14" startColumn="13" endLine="14" endColumn="30" document="1"/> <entry offset="0x8d" hidden="true" document="1"/> <entry offset="0x91" startLine="15" startColumn="21" endLine="15" endColumn="40" document="1"/> <entry offset="0x98" startLine="16" startColumn="17" endLine="16" endColumn="38" document="1"/> <entry offset="0xa0" startLine="23" startColumn="13" endLine="23" endColumn="19" document="1"/> <entry offset="0xa3" startLine="17" startColumn="13" endLine="17" endColumn="30" document="1"/> <entry offset="0xa9" hidden="true" document="1"/> <entry offset="0xad" startLine="18" startColumn="21" endLine="18" endColumn="40" document="1"/> <entry offset="0xb4" startLine="19" startColumn="17" endLine="19" endColumn="38" document="1"/> <entry offset="0xbc" startLine="23" startColumn="13" endLine="23" endColumn="19" document="1"/> <entry offset="0xbf" startLine="20" startColumn="13" endLine="20" endColumn="17" document="1"/> <entry offset="0xc0" startLine="21" startColumn="21" endLine="21" endColumn="42" document="1"/> <entry offset="0xc7" startLine="22" startColumn="17" endLine="22" endColumn="38" document="1"/> <entry offset="0xcf" startLine="23" startColumn="13" endLine="23" endColumn="19" document="1"/> <entry offset="0xd0" startLine="25" startColumn="17" endLine="25" endColumn="40" document="1"/> <entry offset="0xd5" startLine="26" startColumn="13" endLine="26" endColumn="21" document="1"/> <entry offset="0xd8" startLine="27" startColumn="9" endLine="27" endColumn="13" document="1"/> <entry offset="0xd9" startLine="11" startColumn="9" endLine="11" endColumn="23" document="1"/> <entry offset="0xdf" hidden="true" document="1"/> <entry offset="0xe3" startLine="29" startColumn="5" endLine="29" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0xe4"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> <local name="x" il_index="0" il_start="0x0" il_end="0xe4" attributes="0"/> <local name="xx" il_index="1" il_start="0x0" il_end="0xe4" attributes="0"/> <scope startOffset="0x14" endOffset="0x20"> <local name="s" il_index="3" il_start="0x14" il_end="0x20" attributes="0"/> </scope> <scope startOffset="0x5e" endOffset="0x6c"> <local name="s" il_index="5" il_start="0x5e" il_end="0x6c" attributes="0"/> </scope> <scope startOffset="0x6f" endOffset="0xd8"> <local name="newX" il_index="6" il_start="0x6f" il_end="0xd8" attributes="0"/> <scope startOffset="0x91" endOffset="0xa0"> <local name="s2" il_index="9" il_start="0x91" il_end="0xa0" attributes="0"/> </scope> <scope startOffset="0xad" endOffset="0xbc"> <local name="s3" il_index="11" il_start="0xad" il_end="0xbc" attributes="0"/> </scope> <scope startOffset="0xc0" endOffset="0xcf"> <local name="e1" il_index="12" il_start="0xc0" il_end="0xcf" attributes="0"/> </scope> </scope> </scope> </method> </methods> </symbols>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub TestTopConditionDoLoop() Dim source = <compilation> <file><![CDATA[ Imports System Module Module1 Sub Main(args As String()) Dim x As Integer = 0 Do While x < 5 If x < 1 Then Console.WriteLine("<1") ElseIf x < 2 Then Dim s2 As String = "<2" Console.WriteLine(s2) ElseIf x < 3 Then Dim s3 As String = "<3" Console.WriteLine(s3) Else Dim e1 As String = "Else" Console.WriteLine(e1) End If Dim newX As Integer = x + 1 x = newX Loop End Sub End Module ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe) compilation.VerifyPdb("Module1.Main", <symbols> <files> <file id="1" name="" language="VB"/> </files> <entryPoint declaringType="Module1" methodName="Main" parameterNames="args"/> <methods> <method containingType="Module1" name="Main" parameterNames="args"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> <slot kind="0" offset="474"/> <slot kind="1" offset="58"/> <slot kind="1" offset="126"/> <slot kind="0" offset="165"/> <slot kind="1" offset="237"/> <slot kind="0" offset="276"/> <slot kind="0" offset="374"/> <slot kind="1" offset="30"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="4" startColumn="5" endLine="4" endColumn="31" document="1"/> <entry offset="0x1" startLine="6" startColumn="13" endLine="6" endColumn="29" document="1"/> <entry offset="0x3" hidden="true" document="1"/> <entry offset="0x5" startLine="8" startColumn="13" endLine="8" endColumn="26" document="1"/> <entry offset="0xa" hidden="true" document="1"/> <entry offset="0xd" startLine="9" startColumn="17" endLine="9" endColumn="40" document="1"/> <entry offset="0x18" startLine="19" startColumn="13" endLine="19" endColumn="19" document="1"/> <entry offset="0x1b" startLine="10" startColumn="13" endLine="10" endColumn="30" document="1"/> <entry offset="0x20" hidden="true" document="1"/> <entry offset="0x23" startLine="11" startColumn="21" endLine="11" endColumn="40" document="1"/> <entry offset="0x2a" startLine="12" startColumn="17" endLine="12" endColumn="38" document="1"/> <entry offset="0x32" startLine="19" startColumn="13" endLine="19" endColumn="19" document="1"/> <entry offset="0x35" startLine="13" startColumn="13" endLine="13" endColumn="30" document="1"/> <entry offset="0x3b" hidden="true" document="1"/> <entry offset="0x3f" startLine="14" startColumn="21" endLine="14" endColumn="40" document="1"/> <entry offset="0x46" startLine="15" startColumn="17" endLine="15" endColumn="38" document="1"/> <entry offset="0x4e" startLine="19" startColumn="13" endLine="19" endColumn="19" document="1"/> <entry offset="0x51" startLine="16" startColumn="13" endLine="16" endColumn="17" document="1"/> <entry offset="0x52" startLine="17" startColumn="21" endLine="17" endColumn="42" document="1"/> <entry offset="0x59" startLine="18" startColumn="17" endLine="18" endColumn="38" document="1"/> <entry offset="0x61" startLine="19" startColumn="13" endLine="19" endColumn="19" document="1"/> <entry offset="0x62" startLine="21" startColumn="17" endLine="21" endColumn="40" document="1"/> <entry offset="0x66" startLine="22" startColumn="13" endLine="22" endColumn="21" document="1"/> <entry offset="0x68" startLine="23" startColumn="9" endLine="23" endColumn="13" document="1"/> <entry offset="0x69" startLine="7" startColumn="9" endLine="7" endColumn="23" document="1"/> <entry offset="0x6f" hidden="true" document="1"/> <entry offset="0x73" startLine="25" startColumn="5" endLine="25" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x74"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> <local name="x" il_index="0" il_start="0x0" il_end="0x74" attributes="0"/> <scope startOffset="0x5" endOffset="0x68"> <local name="newX" il_index="1" il_start="0x5" il_end="0x68" attributes="0"/> <scope startOffset="0x23" endOffset="0x32"> <local name="s2" il_index="4" il_start="0x23" il_end="0x32" attributes="0"/> </scope> <scope startOffset="0x3f" endOffset="0x4e"> <local name="s3" il_index="6" il_start="0x3f" il_end="0x4e" attributes="0"/> </scope> <scope startOffset="0x52" endOffset="0x61"> <local name="e1" il_index="7" il_start="0x52" il_end="0x61" attributes="0"/> </scope> </scope> </scope> </method> </methods> </symbols>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub TestBottomConditionDoLoop() Dim source = <compilation> <file><![CDATA[ Imports System Module Module1 Sub Main(args As String()) Dim x As Integer = 0 Do If x < 1 Then Console.WriteLine("<1") ElseIf x < 2 Then Dim s2 As String = "<2" Console.WriteLine(s2) ElseIf x < 3 Then Dim s3 As String = "<3" Console.WriteLine(s3) Else Dim e1 As String = "Else" Console.WriteLine(e1) End If Dim newX As Integer = x + 1 x = newX Loop While x < 5 End Sub End Module ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( source, TestOptions.DebugExe) compilation.VerifyPdb("Module1.Main", <symbols> <files> <file id="1" name="" language="VB"/> </files> <entryPoint declaringType="Module1" methodName="Main" parameterNames="args"/> <methods> <method containingType="Module1" name="Main" parameterNames="args"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> <slot kind="0" offset="464"/> <slot kind="1" offset="48"/> <slot kind="1" offset="116"/> <slot kind="0" offset="155"/> <slot kind="1" offset="227"/> <slot kind="0" offset="266"/> <slot kind="0" offset="364"/> <slot kind="1" offset="32"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="4" startColumn="5" endLine="4" endColumn="31" document="1"/> <entry offset="0x1" startLine="6" startColumn="13" endLine="6" endColumn="29" document="1"/> <entry offset="0x3" startLine="8" startColumn="9" endLine="8" endColumn="11" document="1"/> <entry offset="0x4" startLine="9" startColumn="13" endLine="9" endColumn="26" document="1"/> <entry offset="0x9" hidden="true" document="1"/> <entry offset="0xc" startLine="10" startColumn="17" endLine="10" endColumn="40" document="1"/> <entry offset="0x17" startLine="20" startColumn="13" endLine="20" endColumn="19" document="1"/> <entry offset="0x1a" startLine="11" startColumn="13" endLine="11" endColumn="30" document="1"/> <entry offset="0x1f" hidden="true" document="1"/> <entry offset="0x22" startLine="12" startColumn="21" endLine="12" endColumn="40" document="1"/> <entry offset="0x29" startLine="13" startColumn="17" endLine="13" endColumn="38" document="1"/> <entry offset="0x31" startLine="20" startColumn="13" endLine="20" endColumn="19" document="1"/> <entry offset="0x34" startLine="14" startColumn="13" endLine="14" endColumn="30" document="1"/> <entry offset="0x3a" hidden="true" document="1"/> <entry offset="0x3e" startLine="15" startColumn="21" endLine="15" endColumn="40" document="1"/> <entry offset="0x45" startLine="16" startColumn="17" endLine="16" endColumn="38" document="1"/> <entry offset="0x4d" startLine="20" startColumn="13" endLine="20" endColumn="19" document="1"/> <entry offset="0x50" startLine="17" startColumn="13" endLine="17" endColumn="17" document="1"/> <entry offset="0x51" startLine="18" startColumn="21" endLine="18" endColumn="42" document="1"/> <entry offset="0x58" startLine="19" startColumn="17" endLine="19" endColumn="38" document="1"/> <entry offset="0x60" startLine="20" startColumn="13" endLine="20" endColumn="19" document="1"/> <entry offset="0x61" startLine="22" startColumn="17" endLine="22" endColumn="40" document="1"/> <entry offset="0x65" startLine="23" startColumn="13" endLine="23" endColumn="21" document="1"/> <entry offset="0x67" startLine="24" startColumn="9" endLine="24" endColumn="25" document="1"/> <entry offset="0x6e" hidden="true" document="1"/> <entry offset="0x72" startLine="26" startColumn="5" endLine="26" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x73"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> <local name="x" il_index="0" il_start="0x0" il_end="0x73" attributes="0"/> <scope startOffset="0x4" endOffset="0x67"> <local name="newX" il_index="1" il_start="0x4" il_end="0x67" attributes="0"/> <scope startOffset="0x22" endOffset="0x31"> <local name="s2" il_index="4" il_start="0x22" il_end="0x31" attributes="0"/> </scope> <scope startOffset="0x3e" endOffset="0x4d"> <local name="s3" il_index="6" il_start="0x3e" il_end="0x4d" attributes="0"/> </scope> <scope startOffset="0x51" endOffset="0x60"> <local name="e1" il_index="7" il_start="0x51" il_end="0x60" attributes="0"/> </scope> </scope> </scope> </method> </methods> </symbols>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub TestInfiniteLoop() Dim source = <compilation> <file><![CDATA[ Imports System Module Module1 Sub Main(args As String()) Dim x As Integer = 0 Do Dim newX As Integer = x + 1 x = newX Loop End Sub End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe) compilation.VerifyPdb("Module1.Main", <symbols> <files> <file id="1" name="" language="VB"/> </files> <entryPoint declaringType="Module1" methodName="Main" parameterNames="args"/> <methods> <method containingType="Module1" name="Main" parameterNames="args"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> <slot kind="0" offset="52"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="4" startColumn="5" endLine="4" endColumn="31" document="1"/> <entry offset="0x1" startLine="6" startColumn="13" endLine="6" endColumn="29" document="1"/> <entry offset="0x3" startLine="8" startColumn="9" endLine="8" endColumn="11" document="1"/> <entry offset="0x4" startLine="9" startColumn="17" endLine="9" endColumn="40" document="1"/> <entry offset="0x8" startLine="10" startColumn="13" endLine="10" endColumn="21" document="1"/> <entry offset="0xa" startLine="11" startColumn="9" endLine="11" endColumn="13" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0xd"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> <local name="x" il_index="0" il_start="0x0" il_end="0xd" attributes="0"/> <scope startOffset="0x4" endOffset="0xa"> <local name="newX" il_index="1" il_start="0x4" il_end="0xa" attributes="0"/> </scope> </scope> </method> </methods> </symbols>) End Sub <WorkItem(527647, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527647")> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub ExtraSequencePointForEndIf() Dim source = <compilation> <file><![CDATA[ Imports System Public Module MyMod Public Sub Main(args As String()) If (args IsNot Nothing) Then Console.WriteLine("Then") Else Console.WriteLine("Else") End If End Sub End Module ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( source, TestOptions.DebugExe) ' By Design (better than Dev10): <entry offset="0x19" startLine="10" startColumn="9" endLine="10" endColumn="15" document="1"/> compilation.VerifyPdb("MyMod.Main", <symbols> <files> <file id="1" name="" language="VB"/> </files> <entryPoint declaringType="MyMod" methodName="Main" parameterNames="args"/> <methods> <method containingType="MyMod" name="Main" parameterNames="args"> <customDebugInfo> <encLocalSlotMap> <slot kind="1" offset="0"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="5" startColumn="5" endLine="5" endColumn="38" document="1"/> <entry offset="0x1" startLine="6" startColumn="9" endLine="6" endColumn="37" document="1"/> <entry offset="0x6" hidden="true" document="1"/> <entry offset="0x9" startLine="7" startColumn="13" endLine="7" endColumn="38" document="1"/> <entry offset="0x14" startLine="10" startColumn="9" endLine="10" endColumn="15" document="1"/> <entry offset="0x17" startLine="8" startColumn="9" endLine="8" endColumn="13" document="1"/> <entry offset="0x18" startLine="9" startColumn="13" endLine="9" endColumn="38" document="1"/> <entry offset="0x23" startLine="10" startColumn="9" endLine="10" endColumn="15" document="1"/> <entry offset="0x24" startLine="11" startColumn="5" endLine="11" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x25"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> </scope> </method> </methods> </symbols>) End Sub <WorkItem(538821, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538821")> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub MissingSequencePointForOptimizedIfThen() Dim source = <compilation> <file><![CDATA[ Imports System Public Module MyMod Public Sub Main() Console.WriteLine("B") If "x"c = "X"c Then Console.WriteLine("=") End If If "z"c <> "z"c Then Console.WriteLine("<>") End If Console.WriteLine("E") End Sub End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe) CompileAndVerify(compilation).VerifyIL("MyMod.Main", " { // Code size 34 (0x22) .maxstack 1 .locals init (Boolean V_0, Boolean V_1) -IL_0000: nop -IL_0001: ldstr ""B"" IL_0006: call ""Sub System.Console.WriteLine(String)"" IL_000b: nop -IL_000c: ldc.i4.0 IL_000d: stloc.0 IL_000e: br.s IL_0010 -IL_0010: nop -IL_0011: ldc.i4.0 IL_0012: stloc.1 IL_0013: br.s IL_0015 -IL_0015: nop -IL_0016: ldstr ""E"" IL_001b: call ""Sub System.Console.WriteLine(String)"" IL_0020: nop -IL_0021: ret } ", sequencePoints:="MyMod.Main") compilation.VerifyPdb("MyMod.Main", <symbols> <files> <file id="1" name="" language="VB"/> </files> <entryPoint declaringType="MyMod" methodName="Main"/> <methods> <method containingType="MyMod" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="1" offset="34"/> <slot kind="1" offset="117"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="5" startColumn="5" endLine="5" endColumn="22" document="1"/> <entry offset="0x1" startLine="6" startColumn="9" endLine="6" endColumn="31" document="1"/> <entry offset="0xc" startLine="8" startColumn="9" endLine="8" endColumn="28" document="1"/> <entry offset="0x10" startLine="10" startColumn="9" endLine="10" endColumn="15" document="1"/> <entry offset="0x11" startLine="12" startColumn="9" endLine="12" endColumn="29" document="1"/> <entry offset="0x15" startLine="14" startColumn="9" endLine="14" endColumn="15" document="1"/> <entry offset="0x16" startLine="16" startColumn="9" endLine="16" endColumn="31" document="1"/> <entry offset="0x21" startLine="17" startColumn="5" endLine="17" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x22"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> </scope> </method> </methods> </symbols>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub MissingSequencePointForTrivialIfThen() Dim source = <compilation> <file><![CDATA[ Imports System Module Module1 Sub Main() ' one If (False) Then Dim x As String = "hello" Show(x) End If ' two If (False) Then Show("hello") Try Catch ex As Exception Finally ' three If (False) Then Show("hello") End Try End Sub Function Show(s As String) As Integer Console.WriteLine(s) Return 1 End Function End Module ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( source, TestOptions.DebugExe) compilation.VerifyPdb("Module1.Main", <symbols> <files> <file id="1" name="" language="VB"/> </files> <entryPoint declaringType="Module1" methodName="Main"/> <methods> <method containingType="Module1" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="1" offset="0"/> <slot kind="0" offset="33"/> <slot kind="1" offset="118"/> <slot kind="0" offset="172"/> <slot kind="1" offset="245"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="5" startColumn="5" endLine="5" endColumn="15" document="1"/> <entry offset="0x1" startLine="8" startColumn="9" endLine="8" endColumn="24" document="1"/> <entry offset="0x5" startLine="11" startColumn="9" endLine="11" endColumn="15" document="1"/> <entry offset="0x6" startLine="14" startColumn="9" endLine="14" endColumn="24" document="1"/> <entry offset="0xa" hidden="true" document="1"/> <entry offset="0xb" startLine="16" startColumn="9" endLine="16" endColumn="12" document="1"/> <entry offset="0xe" hidden="true" document="1"/> <entry offset="0x15" startLine="17" startColumn="9" endLine="17" endColumn="30" document="1"/> <entry offset="0x1d" hidden="true" document="1"/> <entry offset="0x1f" startLine="18" startColumn="9" endLine="18" endColumn="16" document="1"/> <entry offset="0x20" startLine="20" startColumn="13" endLine="20" endColumn="28" document="1"/> <entry offset="0x25" hidden="true" document="1"/> <entry offset="0x26" startLine="21" startColumn="9" endLine="21" endColumn="16" document="1"/> <entry offset="0x27" startLine="23" startColumn="5" endLine="23" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x28"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> <scope startOffset="0xe" endOffset="0x1c"> <local name="ex" il_index="3" il_start="0xe" il_end="0x1c" attributes="0"/> </scope> </scope> </method> </methods> </symbols>) End Sub <WorkItem(538944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538944")> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub MissingEndWhileSequencePoint() Dim source = <compilation> <file><![CDATA[ Imports System Module MyMod Sub Main(args As String()) Dim x, y, z As ULong, a, b, c As SByte x = 10 y = 20 z = 30 a = 1 b = 2 c = 3 Dim ct As Integer = 100 Do Console.WriteLine("Out={0}", y) y = y + 2 While (x > a) Do While ct - 50 > a + b * 10 b = b + 1 Console.Write("b={0} | ", b) Do Until z <= ct / 4 Console.Write("z={0} | ", z) Do Console.Write("c={0} | ", c) c = c * 2 Loop Until c > ct / 10 z = z - 4 Loop Loop x = x - 5 Console.WriteLine("x={0}", x) End While Loop While (y < 25) End Sub End Module ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( source, TestOptions.DebugExe) ' startLine="33" compilation.VerifyPdb("MyMod.Main", <symbols> <files> <file id="1" name="" language="VB"/> </files> <entryPoint declaringType="MyMod" methodName="Main" parameterNames="args"/> <methods> <method containingType="MyMod" name="Main" parameterNames="args"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> <slot kind="0" offset="7"/> <slot kind="0" offset="10"/> <slot kind="0" offset="22"/> <slot kind="0" offset="25"/> <slot kind="0" offset="28"/> <slot kind="0" offset="145"/> <slot kind="1" offset="521"/> <slot kind="1" offset="421"/> <slot kind="1" offset="289"/> <slot kind="1" offset="258"/> <slot kind="1" offset="174"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="6" startColumn="5" endLine="6" endColumn="31" document="1"/> <entry offset="0x1" startLine="8" startColumn="9" endLine="8" endColumn="15" document="1"/> <entry offset="0x5" startLine="9" startColumn="9" endLine="9" endColumn="15" document="1"/> <entry offset="0x9" startLine="10" startColumn="9" endLine="10" endColumn="15" document="1"/> <entry offset="0xd" startLine="11" startColumn="9" endLine="11" endColumn="14" document="1"/> <entry offset="0xf" startLine="12" startColumn="9" endLine="12" endColumn="14" document="1"/> <entry offset="0x12" startLine="13" startColumn="9" endLine="13" endColumn="14" document="1"/> <entry offset="0x15" startLine="14" startColumn="13" endLine="14" endColumn="32" document="1"/> <entry offset="0x19" startLine="15" startColumn="9" endLine="15" endColumn="11" document="1"/> <entry offset="0x1a" startLine="16" startColumn="13" endLine="16" endColumn="44" document="1"/> <entry offset="0x2b" startLine="17" startColumn="13" endLine="17" endColumn="22" document="1"/> <entry offset="0x43" hidden="true" document="1"/> <entry offset="0x48" hidden="true" document="1"/> <entry offset="0x4d" startLine="20" startColumn="21" endLine="20" endColumn="30" document="1"/> <entry offset="0x54" startLine="21" startColumn="21" endLine="21" endColumn="49" document="1"/> <entry offset="0x66" hidden="true" document="1"/> <entry offset="0x68" startLine="23" startColumn="25" endLine="23" endColumn="53" document="1"/> <entry offset="0x79" startLine="24" startColumn="25" endLine="24" endColumn="27" document="1"/> <entry offset="0x7a" startLine="25" startColumn="29" endLine="25" endColumn="57" document="1"/> <entry offset="0x8c" startLine="26" startColumn="29" endLine="26" endColumn="38" document="1"/> <entry offset="0x93" startLine="27" startColumn="25" endLine="27" endColumn="47" document="1"/> <entry offset="0xa8" hidden="true" document="1"/> <entry offset="0xac" startLine="28" startColumn="25" endLine="28" endColumn="34" document="1"/> <entry offset="0xc4" startLine="29" startColumn="21" endLine="29" endColumn="25" document="1"/> <entry offset="0xc5" startLine="22" startColumn="21" endLine="22" endColumn="41" document="1"/> <entry offset="0xdc" hidden="true" document="1"/> <entry offset="0xe0" startLine="30" startColumn="17" endLine="30" endColumn="21" document="1"/> <entry offset="0xe1" startLine="19" startColumn="17" endLine="19" endColumn="46" document="1"/> <entry offset="0xf1" hidden="true" document="1"/> <entry offset="0xf8" startLine="31" startColumn="17" endLine="31" endColumn="26" document="1"/> <entry offset="0x110" startLine="32" startColumn="17" endLine="32" endColumn="46" document="1"/> <entry offset="0x121" startLine="33" startColumn="13" endLine="33" endColumn="22" document="1"/> <entry offset="0x122" startLine="18" startColumn="13" endLine="18" endColumn="26" document="1"/> <entry offset="0x138" hidden="true" document="1"/> <entry offset="0x13f" startLine="34" startColumn="9" endLine="34" endColumn="28" document="1"/> <entry offset="0x158" hidden="true" document="1"/> <entry offset="0x15f" startLine="35" startColumn="5" endLine="35" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x160"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> <local name="x" il_index="0" il_start="0x0" il_end="0x160" attributes="0"/> <local name="y" il_index="1" il_start="0x0" il_end="0x160" attributes="0"/> <local name="z" il_index="2" il_start="0x0" il_end="0x160" attributes="0"/> <local name="a" il_index="3" il_start="0x0" il_end="0x160" attributes="0"/> <local name="b" il_index="4" il_start="0x0" il_end="0x160" attributes="0"/> <local name="c" il_index="5" il_start="0x0" il_end="0x160" attributes="0"/> <local name="ct" il_index="6" il_start="0x0" il_end="0x160" attributes="0"/> </scope> </method> </methods> </symbols>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub TestImplicitLocals() Dim source = <compilation> <file> Option Explicit Off Option Strict On Imports System Module Module1 Sub Main() x = "Hello" dim y as string = "world" i% = 3 While i &gt; 0 Console.WriteLine("{0}, {1}", x, y) Console.WriteLine(i) q$ = "string" i = i% - 1 End While End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( source, TestOptions.DebugExe) compilation.VerifyPdb("Module1.Main", <symbols> <files> <file id="1" name="" language="VB"/> </files> <entryPoint declaringType="Module1" methodName="Main"/> <methods> <method containingType="Module1" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="0"/> <slot kind="0" offset="56"/> <slot kind="0" offset="180"/> <slot kind="0" offset="25"/> <slot kind="1" offset="72"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="6" startColumn="5" endLine="6" endColumn="15" document="1"/> <entry offset="0x1" startLine="7" startColumn="9" endLine="7" endColumn="20" document="1"/> <entry offset="0x7" startLine="8" startColumn="13" endLine="8" endColumn="34" document="1"/> <entry offset="0xd" startLine="9" startColumn="9" endLine="9" endColumn="15" document="1"/> <entry offset="0xf" hidden="true" document="1"/> <entry offset="0x11" startLine="11" startColumn="13" endLine="11" endColumn="48" document="1"/> <entry offset="0x23" startLine="12" startColumn="13" endLine="12" endColumn="33" document="1"/> <entry offset="0x2a" startLine="13" startColumn="13" endLine="13" endColumn="26" document="1"/> <entry offset="0x30" startLine="14" startColumn="13" endLine="14" endColumn="23" document="1"/> <entry offset="0x34" startLine="15" startColumn="9" endLine="15" endColumn="18" document="1"/> <entry offset="0x35" startLine="10" startColumn="9" endLine="10" endColumn="20" document="1"/> <entry offset="0x3b" hidden="true" document="1"/> <entry offset="0x3f" startLine="16" startColumn="5" endLine="16" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x40"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> <local name="x" il_index="0" il_start="0x0" il_end="0x40" attributes="0"/> <local name="i" il_index="1" il_start="0x0" il_end="0x40" attributes="0"/> <local name="q" il_index="2" il_start="0x0" il_end="0x40" attributes="0"/> <local name="y" il_index="3" il_start="0x0" il_end="0x40" attributes="0"/> </scope> </method> </methods> </symbols>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub AddRemoveHandler() Dim source = <compilation> <file><![CDATA[ Imports System Module Module1 Sub Main(args As String()) Dim del As System.EventHandler = Sub(sender As Object, a As EventArgs) Console.Write("unload") Dim v = AppDomain.CreateDomain("qq") AddHandler (v.DomainUnload), del RemoveHandler (v.DomainUnload), del AppDomain.Unload(v) End Sub End Module ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( source, TestOptions.DebugExe) compilation.VerifyPdb("Module1.Main", <symbols> <files> <file id="1" name="" language="VB"/> </files> <entryPoint declaringType="Module1" methodName="Main" parameterNames="args"/> <methods> <method containingType="Module1" name="Main" parameterNames="args"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> <slot kind="0" offset="123"/> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>0</methodOrdinal> <lambda offset="46"/> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="4" startColumn="5" endLine="4" endColumn="31" document="1"/> <entry offset="0x1" startLine="5" startColumn="13" endLine="6" endColumn="74" document="1"/> <entry offset="0x26" startLine="8" startColumn="13" endLine="8" endColumn="45" document="1"/> <entry offset="0x31" startLine="10" startColumn="9" endLine="10" endColumn="41" document="1"/> <entry offset="0x39" startLine="11" startColumn="9" endLine="11" endColumn="44" document="1"/> <entry offset="0x41" startLine="13" startColumn="9" endLine="13" endColumn="28" document="1"/> <entry offset="0x48" startLine="14" startColumn="5" endLine="14" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x49"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> <local name="del" il_index="0" il_start="0x0" il_end="0x49" attributes="0"/> <local name="v" il_index="1" il_start="0x0" il_end="0x49" attributes="0"/> </scope> </method> </methods> </symbols>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub SelectCase_NoCaseBlocks() Dim source = <compilation> <file><![CDATA[ Imports System Module Module1 Sub Main() Dim num As Integer = 0 Select Case num End Select End Sub End Module ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe) compilation.VerifyPdb("Module1.Main", <symbols> <files> <file id="1" name="" language="VB"/> </files> <entryPoint declaringType="Module1" methodName="Main"/> <methods> <method containingType="Module1" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="3" startColumn="5" endLine="3" endColumn="15" document="1"/> <entry offset="0x1" startLine="4" startColumn="13" endLine="4" endColumn="31" document="1"/> <entry offset="0x3" startLine="5" startColumn="9" endLine="5" endColumn="24" document="1"/> <entry offset="0x4" startLine="6" startColumn="9" endLine="6" endColumn="19" document="1"/> <entry offset="0x5" startLine="7" startColumn="5" endLine="7" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x6"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> <local name="num" il_index="0" il_start="0x0" il_end="0x6" attributes="0"/> </scope> </method> </methods> </symbols>) CompileAndVerify(compilation, expectedOutput:="") End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub SelectCase_SingleCaseStatement() Dim source = <compilation> <file><![CDATA[ Imports System Module Module1 Sub Main() Dim num As Integer = 0 Select Case num Case 1 End Select Select Case num Case Else End Select End Sub End Module ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe) compilation.VerifyPdb("Module1.Main", <symbols> <files> <file id="1" name="" language="VB"/> </files> <entryPoint declaringType="Module1" methodName="Main"/> <methods> <method containingType="Module1" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="3" startColumn="5" endLine="3" endColumn="15" document="1"/> <entry offset="0x1" startLine="4" startColumn="13" endLine="4" endColumn="31" document="1"/> <entry offset="0x3" startLine="5" startColumn="9" endLine="5" endColumn="24" document="1"/> <entry offset="0xa" startLine="6" startColumn="13" endLine="6" endColumn="19" document="1"/> <entry offset="0xd" startLine="7" startColumn="9" endLine="7" endColumn="19" document="1"/> <entry offset="0xe" startLine="9" startColumn="9" endLine="9" endColumn="24" document="1"/> <entry offset="0x11" startLine="10" startColumn="13" endLine="10" endColumn="22" document="1"/> <entry offset="0x14" startLine="11" startColumn="9" endLine="11" endColumn="19" document="1"/> <entry offset="0x15" startLine="12" startColumn="5" endLine="12" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x16"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> <local name="num" il_index="0" il_start="0x0" il_end="0x16" attributes="0"/> </scope> </method> </methods> </symbols>) CompileAndVerify(compilation, expectedOutput:="") End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub SelectCase_OnlyCaseStatements() Dim source = <compilation> <file><![CDATA[ Imports System Module Module1 Sub Main() Dim num As Integer = 0 Select Case num Case 1 Case 2 Case 0, 3 To 8 Case Else End Select End Sub End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe) CompileAndVerify(compilation).VerifyIL("Module1.Main", " { // Code size 55 (0x37) .maxstack 2 .locals init (Integer V_0, //num Integer V_1, Boolean V_2) -IL_0000: nop -IL_0001: ldc.i4.0 IL_0002: stloc.0 -IL_0003: nop IL_0004: ldloc.0 IL_0005: stloc.1 -IL_0006: ldloc.1 IL_0007: ldc.i4.1 IL_0008: ceq IL_000a: stloc.2 ~IL_000b: ldloc.2 IL_000c: brfalse.s IL_0010 IL_000e: br.s IL_0035 -IL_0010: ldloc.1 IL_0011: ldc.i4.2 IL_0012: ceq IL_0014: stloc.2 ~IL_0015: ldloc.2 IL_0016: brfalse.s IL_001a IL_0018: br.s IL_0035 -IL_001a: ldloc.1 IL_001b: brfalse.s IL_002d IL_001d: ldloc.1 IL_001e: ldc.i4.3 IL_001f: blt.s IL_002a IL_0021: ldloc.1 IL_0022: ldc.i4.8 IL_0023: cgt IL_0025: ldc.i4.0 IL_0026: ceq IL_0028: br.s IL_002b IL_002a: ldc.i4.0 IL_002b: br.s IL_002e IL_002d: ldc.i4.1 IL_002e: stloc.2 ~IL_002f: ldloc.2 IL_0030: brfalse.s IL_0034 IL_0032: br.s IL_0035 -IL_0034: nop -IL_0035: nop -IL_0036: ret } ", sequencePoints:="Module1.Main") compilation.VerifyPdb("Module1.Main", <symbols> <files> <file id="1" name="" language="VB"/> </files> <entryPoint declaringType="Module1" methodName="Main"/> <methods> <method containingType="Module1" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> <slot kind="15" offset="32"/> <slot kind="1" offset="32"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="3" startColumn="5" endLine="3" endColumn="15" document="1"/> <entry offset="0x1" startLine="4" startColumn="13" endLine="4" endColumn="31" document="1"/> <entry offset="0x3" startLine="5" startColumn="9" endLine="5" endColumn="24" document="1"/> <entry offset="0x6" startLine="6" startColumn="13" endLine="6" endColumn="19" document="1"/> <entry offset="0xb" hidden="true" document="1"/> <entry offset="0x10" startLine="7" startColumn="13" endLine="7" endColumn="19" document="1"/> <entry offset="0x15" hidden="true" document="1"/> <entry offset="0x1a" startLine="8" startColumn="13" endLine="8" endColumn="27" document="1"/> <entry offset="0x2f" hidden="true" document="1"/> <entry offset="0x34" startLine="9" startColumn="13" endLine="9" endColumn="22" document="1"/> <entry offset="0x35" startLine="10" startColumn="9" endLine="10" endColumn="19" document="1"/> <entry offset="0x36" startLine="11" startColumn="5" endLine="11" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x37"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> <local name="num" il_index="0" il_start="0x0" il_end="0x37" attributes="0"/> </scope> </method> </methods> </symbols>) CompileAndVerify(compilation, expectedOutput:="") End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub SelectCase_SwitchTable() Dim source = <compilation> <file><![CDATA[ Imports System Module Module1 Sub Main() Dim num As Integer = 0 Select Case num Case 1 Console.WriteLine("1") Case 2 Console.WriteLine("2") Case 0, 3, 4, 5, 6, Is = 7, 8 Case Else Console.WriteLine("Else") End Select End Sub End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe) compilation.VerifyPdb("Module1.Main", <symbols> <files> <file id="1" name="" language="VB"/> </files> <entryPoint declaringType="Module1" methodName="Main"/> <methods> <method containingType="Module1" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="3" startColumn="5" endLine="3" endColumn="15" document="1"/> <entry offset="0x1" startLine="4" startColumn="13" endLine="4" endColumn="31" document="1"/> <entry offset="0x3" startLine="5" startColumn="9" endLine="5" endColumn="24" document="1"/> <entry offset="0x30" startLine="6" startColumn="13" endLine="6" endColumn="19" document="1"/> <entry offset="0x31" startLine="7" startColumn="17" endLine="7" endColumn="39" document="1"/> <entry offset="0x3e" startLine="8" startColumn="13" endLine="8" endColumn="19" document="1"/> <entry offset="0x3f" startLine="9" startColumn="17" endLine="9" endColumn="39" document="1"/> <entry offset="0x4c" startLine="10" startColumn="13" endLine="10" endColumn="42" document="1"/> <entry offset="0x4f" startLine="11" startColumn="13" endLine="11" endColumn="22" document="1"/> <entry offset="0x50" startLine="12" startColumn="17" endLine="12" endColumn="42" document="1"/> <entry offset="0x5d" startLine="13" startColumn="9" endLine="13" endColumn="19" document="1"/> <entry offset="0x5e" startLine="14" startColumn="5" endLine="14" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x5f"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> <local name="num" il_index="0" il_start="0x0" il_end="0x5f" attributes="0"/> </scope> </method> </methods> </symbols>) CompileAndVerify(compilation, expectedOutput:="") End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub SelectCase_SwitchTable_TempUsed() Dim source = <compilation> <file><![CDATA[ Imports System Module Module1 Sub Main() Dim num As Integer = 0 Select Case num + 1 Case 1 Console.WriteLine("") Case 2 Console.WriteLine("2") Case 0, 3, 4, 5, 6, Is = 7, 8 Console.WriteLine("0") Case Else Console.WriteLine("Else") End Select End Sub End Module ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe) compilation.VerifyPdb("Module1.Main", <symbols> <files> <file id="1" name="" language="VB"/> </files> <entryPoint declaringType="Module1" methodName="Main"/> <methods> <method containingType="Module1" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> <slot kind="15" offset="32"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="3" startColumn="5" endLine="3" endColumn="15" document="1"/> <entry offset="0x1" startLine="4" startColumn="13" endLine="4" endColumn="31" document="1"/> <entry offset="0x3" startLine="5" startColumn="9" endLine="5" endColumn="28" document="1"/> <entry offset="0x34" startLine="6" startColumn="13" endLine="6" endColumn="19" document="1"/> <entry offset="0x35" startLine="7" startColumn="17" endLine="7" endColumn="38" document="1"/> <entry offset="0x42" startLine="8" startColumn="13" endLine="8" endColumn="19" document="1"/> <entry offset="0x43" startLine="9" startColumn="17" endLine="9" endColumn="39" document="1"/> <entry offset="0x50" startLine="10" startColumn="13" endLine="10" endColumn="42" document="1"/> <entry offset="0x51" startLine="11" startColumn="17" endLine="11" endColumn="39" document="1"/> <entry offset="0x5e" startLine="12" startColumn="13" endLine="12" endColumn="22" document="1"/> <entry offset="0x5f" startLine="13" startColumn="17" endLine="13" endColumn="42" document="1"/> <entry offset="0x6c" startLine="14" startColumn="9" endLine="14" endColumn="19" document="1"/> <entry offset="0x6d" startLine="15" startColumn="5" endLine="15" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x6e"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> <local name="num" il_index="0" il_start="0x0" il_end="0x6e" attributes="0"/> </scope> </method> </methods> </symbols>) CompileAndVerify(compilation, expectedOutput:="") End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub SelectCase_IfList() Dim source = <compilation> <file><![CDATA[ Imports System Module Module1 Sub Main() Dim num As Integer = 0 Select Case num Case 1 Console.WriteLine("1") Case 2 Console.WriteLine("2") Case 0, >= 3, <= 8 Case Else Console.WriteLine("Else") End Select End Sub End Module ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe) compilation.VerifyPdb("Module1.Main", <symbols> <files> <file id="1" name="" language="VB"/> </files> <entryPoint declaringType="Module1" methodName="Main"/> <methods> <method containingType="Module1" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> <slot kind="15" offset="32"/> <slot kind="1" offset="32"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="3" startColumn="5" endLine="3" endColumn="15" document="1"/> <entry offset="0x1" startLine="4" startColumn="13" endLine="4" endColumn="31" document="1"/> <entry offset="0x3" startLine="5" startColumn="9" endLine="5" endColumn="24" document="1"/> <entry offset="0x6" startLine="6" startColumn="13" endLine="6" endColumn="19" document="1"/> <entry offset="0xb" hidden="true" document="1"/> <entry offset="0xe" startLine="7" startColumn="17" endLine="7" endColumn="39" document="1"/> <entry offset="0x1b" startLine="8" startColumn="13" endLine="8" endColumn="19" document="1"/> <entry offset="0x20" hidden="true" document="1"/> <entry offset="0x23" startLine="9" startColumn="17" endLine="9" endColumn="39" document="1"/> <entry offset="0x30" startLine="10" startColumn="13" endLine="10" endColumn="31" document="1"/> <entry offset="0x42" hidden="true" document="1"/> <entry offset="0x47" startLine="12" startColumn="17" endLine="12" endColumn="42" document="1"/> <entry offset="0x52" startLine="13" startColumn="9" endLine="13" endColumn="19" document="1"/> <entry offset="0x53" startLine="14" startColumn="5" endLine="14" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x54"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> <local name="num" il_index="0" il_start="0x0" il_end="0x54" attributes="0"/> </scope> </method> </methods> </symbols>) CompileAndVerify(compilation, expectedOutput:="") End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub SelectCase_IfList_TempUsed() Dim source = <compilation> <file><![CDATA[ Imports System Module Module1 Sub Main() Dim num As Integer = 0 Select Case num + 1 Case 1 Console.WriteLine("") Case 2 Console.WriteLine("2") Case 0, >= 3, <= 8 Console.WriteLine("0") Case Else Console.WriteLine("Else") End Select End Sub End Module ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe) compilation.VerifyPdb("Module1.Main", <symbols> <files> <file id="1" name="" language="VB"/> </files> <entryPoint declaringType="Module1" methodName="Main"/> <methods> <method containingType="Module1" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> <slot kind="15" offset="32"/> <slot kind="1" offset="32"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="3" startColumn="5" endLine="3" endColumn="15" document="1"/> <entry offset="0x1" startLine="4" startColumn="13" endLine="4" endColumn="31" document="1"/> <entry offset="0x3" startLine="5" startColumn="9" endLine="5" endColumn="28" document="1"/> <entry offset="0x8" startLine="6" startColumn="13" endLine="6" endColumn="19" document="1"/> <entry offset="0xd" hidden="true" document="1"/> <entry offset="0x10" startLine="7" startColumn="17" endLine="7" endColumn="38" document="1"/> <entry offset="0x1d" startLine="8" startColumn="13" endLine="8" endColumn="19" document="1"/> <entry offset="0x22" hidden="true" document="1"/> <entry offset="0x25" startLine="9" startColumn="17" endLine="9" endColumn="39" document="1"/> <entry offset="0x32" startLine="10" startColumn="13" endLine="10" endColumn="31" document="1"/> <entry offset="0x44" hidden="true" document="1"/> <entry offset="0x47" startLine="11" startColumn="17" endLine="11" endColumn="39" document="1"/> <entry offset="0x54" startLine="13" startColumn="17" endLine="13" endColumn="42" document="1"/> <entry offset="0x5f" startLine="14" startColumn="9" endLine="14" endColumn="19" document="1"/> <entry offset="0x60" startLine="15" startColumn="5" endLine="15" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x61"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> <local name="num" il_index="0" il_start="0x0" il_end="0x61" attributes="0"/> </scope> </method> </methods> </symbols>) CompileAndVerify(compilation, expectedOutput:="") End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub SelectCase_String_SwitchTable_Hash() Dim source = <compilation> <file><![CDATA[ Imports System Module Module1 Sub Main() Dim str As String = "00" Select Case str Case "01" Console.WriteLine("01") Case "02" Console.WriteLine("02") Case "00", "03", "04", "05", "06", "07", "08" Case Else Console.WriteLine("Else") End Select End Sub End Module ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe) compilation.VerifyPdb("Module1.Main", <symbols> <files> <file id="1" name="" language="VB"/> </files> <entryPoint declaringType="Module1" methodName="Main"/> <methods> <method containingType="Module1" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> <slot kind="temp"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="3" startColumn="5" endLine="3" endColumn="15" document="1"/> <entry offset="0x1" startLine="4" startColumn="13" endLine="4" endColumn="33" document="1"/> <entry offset="0x7" startLine="5" startColumn="9" endLine="5" endColumn="24" document="1"/> <entry offset="0x135" startLine="6" startColumn="13" endLine="6" endColumn="22" document="1"/> <entry offset="0x136" startLine="7" startColumn="17" endLine="7" endColumn="40" document="1"/> <entry offset="0x143" startLine="8" startColumn="13" endLine="8" endColumn="22" document="1"/> <entry offset="0x144" startLine="9" startColumn="17" endLine="9" endColumn="40" document="1"/> <entry offset="0x151" startLine="10" startColumn="13" endLine="10" endColumn="58" document="1"/> <entry offset="0x154" startLine="11" startColumn="13" endLine="11" endColumn="22" document="1"/> <entry offset="0x155" startLine="12" startColumn="17" endLine="12" endColumn="42" document="1"/> <entry offset="0x162" startLine="13" startColumn="9" endLine="13" endColumn="19" document="1"/> <entry offset="0x163" startLine="14" startColumn="5" endLine="14" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x164"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> <local name="str" il_index="0" il_start="0x0" il_end="0x164" attributes="0"/> </scope> </method> </methods> </symbols>) CompileAndVerify(compilation, expectedOutput:="") End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub SelectCase_String_SwitchTable_NonHash() Dim source = <compilation> <file><![CDATA[ Imports System Module Module1 Sub Main() Dim str As String = "00" Select Case str Case "01" Console.WriteLine("01") Case "02" Case "00" Console.WriteLine("00") Case Else End Select End Sub End Module ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe) compilation.VerifyPdb("Module1.Main", <symbols> <files> <file id="1" name="" language="VB"/> </files> <entryPoint declaringType="Module1" methodName="Main"/> <methods> <method containingType="Module1" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="3" startColumn="5" endLine="3" endColumn="15" document="1"/> <entry offset="0x1" startLine="4" startColumn="13" endLine="4" endColumn="33" document="1"/> <entry offset="0x7" startLine="5" startColumn="9" endLine="5" endColumn="24" document="1"/> <entry offset="0x34" startLine="6" startColumn="13" endLine="6" endColumn="22" document="1"/> <entry offset="0x35" startLine="7" startColumn="17" endLine="7" endColumn="40" document="1"/> <entry offset="0x42" startLine="8" startColumn="13" endLine="8" endColumn="22" document="1"/> <entry offset="0x45" startLine="9" startColumn="13" endLine="9" endColumn="22" document="1"/> <entry offset="0x46" startLine="10" startColumn="17" endLine="10" endColumn="40" document="1"/> <entry offset="0x53" startLine="11" startColumn="13" endLine="11" endColumn="22" document="1"/> <entry offset="0x56" startLine="12" startColumn="9" endLine="12" endColumn="19" document="1"/> <entry offset="0x57" startLine="13" startColumn="5" endLine="13" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x58"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> <local name="str" il_index="0" il_start="0x0" il_end="0x58" attributes="0"/> </scope> </method> </methods> </symbols>) CompileAndVerify(compilation, expectedOutput:="00") End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub SelectCase_String_IfList() Dim source = <compilation> <file><![CDATA[ Imports System Module Module1 Sub Main() Dim str As String = "00" Select Case str Case "01" Console.WriteLine("01") Case "02", 3.ToString() Case "00" Console.WriteLine("00") End Select End Sub End Module ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe) compilation.VerifyPdb("Module1.Main", <symbols> <files> <file id="1" name="" language="VB"/> </files> <entryPoint declaringType="Module1" methodName="Main"/> <methods> <method containingType="Module1" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> <slot kind="15" offset="34"/> <slot kind="1" offset="34"/> <slot kind="temp"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="3" startColumn="5" endLine="3" endColumn="15" document="1"/> <entry offset="0x1" startLine="4" startColumn="13" endLine="4" endColumn="33" document="1"/> <entry offset="0x7" startLine="5" startColumn="9" endLine="5" endColumn="24" document="1"/> <entry offset="0xa" startLine="6" startColumn="13" endLine="6" endColumn="22" document="1"/> <entry offset="0x1a" hidden="true" document="1"/> <entry offset="0x1d" startLine="7" startColumn="17" endLine="7" endColumn="40" document="1"/> <entry offset="0x2a" startLine="8" startColumn="13" endLine="8" endColumn="36" document="1"/> <entry offset="0x4f" hidden="true" document="1"/> <entry offset="0x54" startLine="9" startColumn="13" endLine="9" endColumn="22" document="1"/> <entry offset="0x64" hidden="true" document="1"/> <entry offset="0x67" startLine="10" startColumn="17" endLine="10" endColumn="40" document="1"/> <entry offset="0x72" startLine="11" startColumn="9" endLine="11" endColumn="19" document="1"/> <entry offset="0x73" startLine="12" startColumn="5" endLine="12" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x74"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> <local name="str" il_index="0" il_start="0x0" il_end="0x74" attributes="0"/> </scope> </method> </methods> </symbols>) CompileAndVerify(compilation, expectedOutput:="00") End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub DontEmit_AnonymousType_NoKeys() Dim source = <compilation> <file><![CDATA[ Class C1 Sub Method() Dim o = New With { .a = 1 } End Sub End Class ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugDll) compilation.VerifyPdb( <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="C1" name="Method"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="2" startColumn="5" endLine="2" endColumn="17" document="1"/> <entry offset="0x1" startLine="3" startColumn="13" endLine="3" endColumn="36" document="1"/> <entry offset="0x8" startLine="4" startColumn="5" endLine="4" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x9"> <currentnamespace name=""/> <local name="o" il_index="0" il_start="0x0" il_end="0x9" attributes="0"/> </scope> </method> </methods> </symbols>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub DontEmit_AnonymousType_WithKeys() Dim source = <compilation> <file><![CDATA[ Class C1 Sub Method() Dim o = New With { Key .a = 1 } End Sub End Class ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugDll) compilation.VerifyPdb( <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="C1" name="Method"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="2" startColumn="5" endLine="2" endColumn="17" document="1"/> <entry offset="0x1" startLine="3" startColumn="13" endLine="3" endColumn="40" document="1"/> <entry offset="0x8" startLine="4" startColumn="5" endLine="4" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x9"> <currentnamespace name=""/> <local name="o" il_index="0" il_start="0x0" il_end="0x9" attributes="0"/> </scope> </method> </methods> </symbols>) End Sub <WorkItem(727419, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/727419")> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub Bug727419() Dim source = <compilation> <file><![CDATA[ Option Strict Off Option Explicit Off Imports System Class GooDerived Public Sub ComputeMatrix(ByVal rank As Integer) Dim I As Integer Dim J As Long Dim q() As Long Dim count As Long Dim dims() As Long ' allocate space for arrays ReDim q(rank) ReDim dims(rank) ' create the dimensions count = 1 For I = 0 To rank - 1 q(I) = 0 dims(I) = CLng(2 ^ I) count *= dims(I) Next I End Sub End Class Module Variety Sub Main() Dim a As New GooDerived() a.ComputeMatrix(2) End Sub End Module ' End of File ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( source, TestOptions.DebugExe) compilation.VerifyPdb("GooDerived.ComputeMatrix", <symbols> <files> <file id="1" name="" language="VB"/> </files> <entryPoint declaringType="Variety" methodName="Main"/> <methods> <method containingType="GooDerived" name="ComputeMatrix" parameterNames="rank"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> <slot kind="0" offset="30"/> <slot kind="0" offset="53"/> <slot kind="0" offset="78"/> <slot kind="0" offset="105"/> <slot kind="11" offset="271"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="6" startColumn="5" endLine="6" endColumn="52" document="1"/> <entry offset="0x1" startLine="14" startColumn="15" endLine="14" endColumn="22" document="1"/> <entry offset="0xa" startLine="15" startColumn="15" endLine="15" endColumn="25" document="1"/> <entry offset="0x14" startLine="18" startColumn="9" endLine="18" endColumn="18" document="1"/> <entry offset="0x17" startLine="19" startColumn="9" endLine="19" endColumn="30" document="1"/> <entry offset="0x1e" hidden="true" document="1"/> <entry offset="0x20" startLine="20" startColumn="13" endLine="20" endColumn="21" document="1"/> <entry offset="0x25" startLine="21" startColumn="13" endLine="21" endColumn="34" document="1"/> <entry offset="0x3f" startLine="22" startColumn="13" endLine="22" endColumn="29" document="1"/> <entry offset="0x46" startLine="23" startColumn="9" endLine="23" endColumn="15" document="1"/> <entry offset="0x4a" hidden="true" document="1"/> <entry offset="0x4f" startLine="24" startColumn="5" endLine="24" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x50"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> <local name="I" il_index="0" il_start="0x0" il_end="0x50" attributes="0"/> <local name="J" il_index="1" il_start="0x0" il_end="0x50" attributes="0"/> <local name="q" il_index="2" il_start="0x0" il_end="0x50" attributes="0"/> <local name="count" il_index="3" il_start="0x0" il_end="0x50" attributes="0"/> <local name="dims" il_index="4" il_start="0x0" il_end="0x50" attributes="0"/> </scope> </method> </methods> </symbols>) End Sub <WorkItem(722627, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/722627")> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub Bug722627() Dim source = <compilation> <file><![CDATA[ Imports System Friend Module SubMod Sub Main() L0: GoTo L2 L1: Exit Sub L2: GoTo L1 End Sub End Module ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( source, TestOptions.DebugExe) compilation.VerifyPdb("SubMod.Main", <symbols> <files> <file id="1" name="" language="VB"/> </files> <entryPoint declaringType="SubMod" methodName="Main"/> <methods> <method containingType="SubMod" name="Main"> <sequencePoints> <entry offset="0x0" startLine="3" startColumn="5" endLine="3" endColumn="15" document="1"/> <entry offset="0x1" startLine="4" startColumn="1" endLine="4" endColumn="4" document="1"/> <entry offset="0x2" startLine="5" startColumn="9" endLine="5" endColumn="16" document="1"/> <entry offset="0x4" startLine="6" startColumn="1" endLine="6" endColumn="4" document="1"/> <entry offset="0x5" startLine="7" startColumn="9" endLine="7" endColumn="17" document="1"/> <entry offset="0x7" startLine="8" startColumn="1" endLine="8" endColumn="4" document="1"/> <entry offset="0x8" startLine="9" startColumn="9" endLine="9" endColumn="16" document="1"/> <entry offset="0xa" startLine="10" startColumn="5" endLine="10" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0xb"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> </scope> </method> </methods> </symbols>) End Sub <WorkItem(543703, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543703")> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub DontIncludeMethodAttributesInSeqPoint() Dim source = <compilation> <file><![CDATA[ Imports System Module M1 Sub Main() S() End Sub <System.Runtime.InteropServices.PreserveSigAttribute()> <CLSCompliantAttribute(False)> Public Sub S() End Sub End Module ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugDll) compilation.VerifyPdb( <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="M1" name="Main"> <sequencePoints> <entry offset="0x0" startLine="3" startColumn="5" endLine="3" endColumn="15" document="1"/> <entry offset="0x1" startLine="4" startColumn="9" endLine="4" endColumn="12" document="1"/> <entry offset="0x7" startLine="5" startColumn="5" endLine="5" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x8"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> </scope> </method> <method containingType="M1" name="S"> <sequencePoints> <entry offset="0x0" startLine="9" startColumn="5" endLine="9" endColumn="19" document="1"/> <entry offset="0x1" startLine="11" startColumn="5" endLine="11" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x2"> <importsforward declaringType="M1" methodName="Main"/> </scope> </method> </methods> </symbols>) End Sub <WorkItem(529300, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529300")> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub DontShowOperatorNameCTypeInLocals() Dim source = <compilation> <file><![CDATA[ Imports System Module Module1 Class B2 Public f As Integer Public Sub New(x As Integer) f = x End Sub Shared Widening Operator CType(x As Integer) As B2 Return New B2(x) End Operator End Class Sub Main() Dim x As Integer = 11 Dim b2 As B2 = x End Sub End Module ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugDll) compilation.VerifyPdb( <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="Module1" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> <slot kind="0" offset="35"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="17" startColumn="5" endLine="17" endColumn="15" document="1"/> <entry offset="0x1" startLine="18" startColumn="13" endLine="18" endColumn="30" document="1"/> <entry offset="0x4" startLine="19" startColumn="13" endLine="19" endColumn="25" document="1"/> <entry offset="0xb" startLine="20" startColumn="5" endLine="20" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0xc"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> <local name="x" il_index="0" il_start="0x0" il_end="0xc" attributes="0"/> <local name="b2" il_index="1" il_start="0x0" il_end="0xc" attributes="0"/> </scope> </method> <method containingType="Module1+B2" name=".ctor" parameterNames="x"> <sequencePoints> <entry offset="0x0" startLine="8" startColumn="9" endLine="8" endColumn="37" document="1"/> <entry offset="0x8" startLine="9" startColumn="13" endLine="9" endColumn="18" document="1"/> <entry offset="0xf" startLine="10" startColumn="9" endLine="10" endColumn="16" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x10"> <importsforward declaringType="Module1" methodName="Main"/> </scope> </method> <method containingType="Module1+B2" name="op_Implicit" parameterNames="x"> <customDebugInfo> <encLocalSlotMap> <slot kind="21" offset="-1"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="12" startColumn="9" endLine="12" endColumn="59" document="1"/> <entry offset="0x1" startLine="13" startColumn="13" endLine="13" endColumn="29" document="1"/> <entry offset="0xa" startLine="14" startColumn="9" endLine="14" endColumn="21" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0xc"> <importsforward declaringType="Module1" methodName="Main"/> </scope> </method> </methods> </symbols>) End Sub <WorkItem(760994, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/760994")> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub Bug760994() Dim source = <compilation> <file><![CDATA[ Imports System Class CLAZZ Public FLD1 As Integer = 1 Public Event Load As Action Public FLD2 As Integer = 1 Public Sub New() End Sub Private Sub frmMain_Load() Handles Me.Load End Sub End Class Module Program Sub Main(args As String()) Dim c As New CLAZZ End Sub End Module ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugDll) compilation.VerifyPdb("CLAZZ..ctor", <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="CLAZZ" name=".ctor"> <sequencePoints> <entry offset="0x0" startLine="8" startColumn="5" endLine="8" endColumn="21" document="1"/> <entry offset="0x1b" startLine="4" startColumn="12" endLine="4" endColumn="31" document="1"/> <entry offset="0x22" startLine="6" startColumn="12" endLine="6" endColumn="31" document="1"/> <entry offset="0x29" startLine="10" startColumn="5" endLine="10" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x2a"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> </scope> </method> </methods> </symbols>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub WRN_PDBConstantStringValueTooLong() Dim longStringValue = New String("a"c, 2050) Dim source = <compilation> <file> Imports System Module Module1 Sub Main() Const goo as String = "<%= longStringValue %>" Console.WriteLine("Hello Word.") Console.WriteLine(goo) End Sub End Module </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe) Dim exebits = New IO.MemoryStream() Dim pdbbits = New IO.MemoryStream() Dim result = compilation.Emit(exebits, pdbbits) result.Diagnostics.Verify() 'this new warning was abandoned 'result.Diagnostics.Verify(Diagnostic(ERRID.WRN_PDBConstantStringValueTooLong).WithArguments("goo", longStringValue.Substring(0, 20) & "...")) ''ensure that the warning is suppressable 'compilation = CreateCompilationWithMscorlibAndVBRuntime(source, OptionsExe.WithDebugInformationKind(Common.DebugInformationKind.Full).WithOptimizations(False). ' WithSpecificDiagnosticOptions(New Dictionary(Of Integer, ReportWarning) From {{CInt(ERRID.WRN_PDBConstantStringValueTooLong), ReportWarning.Suppress}})) 'result = compilation.Emit(exebits, Nothing, "DontCare", pdbbits, Nothing) 'result.Diagnostics.Verify() ''ensure that the warning can be turned into an error 'compilation = CreateCompilationWithMscorlibAndVBRuntime(source, OptionsExe.WithDebugInformationKind(Common.DebugInformationKind.Full).WithOptimizations(False). ' WithSpecificDiagnosticOptions(New Dictionary(Of Integer, ReportWarning) From {{CInt(ERRID.WRN_PDBConstantStringValueTooLong), ReportWarning.Error}})) 'result = compilation.Emit(exebits, Nothing, "DontCare", pdbbits, Nothing) 'Assert.False(result.Success) 'result.Diagnostics.Verify(Diagnostic(ERRID.WRN_PDBConstantStringValueTooLong).WithArguments("goo", longStringValue.Substring(0, 20) & "...").WithWarningAsError(True), ' Diagnostic(ERRID.ERR_WarningTreatedAsError).WithArguments("The value assigned to the constant string 'goo' is too long to be used in a PDB file. Consider shortening the value, otherwise the string's value will not be visible in the debugger. Only the debug experience is affected.")) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub NoDebugInfoForEmbeddedSymbols() Dim source = <compilation> <file> Imports Microsoft.VisualBasic.Strings Public Class C Public Shared Function F(z As Integer) As Char Return ChrW(z) End Function End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugDll.WithEmbedVbCoreRuntime(True)) ' Dev11 generates debug info for embedded symbols. There is no reason to do so since the source code is not available to the user. compilation.VerifyPdb( <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="C" name="F" parameterNames="z"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="4" startColumn="5" endLine="4" endColumn="51" document="1"/> <entry offset="0x1" startLine="5" startColumn="9" endLine="5" endColumn="23" document="1"/> <entry offset="0xa" startLine="6" startColumn="5" endLine="6" endColumn="17" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0xc"> <type name="Microsoft.VisualBasic.Strings" importlevel="file"/> <currentnamespace name=""/> <local name="F" il_index="0" il_start="0x0" il_end="0xc" attributes="0"/> </scope> </method> </methods> </symbols>) End Sub <WorkItem(797482, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/797482")> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub Bug797482() Dim source = <compilation> <file><![CDATA[ Imports System Module Module1 Sub Main() Console.WriteLine(MakeIncrementer(5)(2)) End Sub Function MakeIncrementer(n As Integer) As Func(Of Integer, Integer) Return Function(i) Return i + n End Function End Function End Module ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugDll) compilation.VerifyPdb("Module1.MakeIncrementer", <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="Module1" name="MakeIncrementer" parameterNames="n"> <customDebugInfo> <encLocalSlotMap> <slot kind="30" offset="-1"/> <slot kind="0" offset="-1"/> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>1</methodOrdinal> <closure offset="-1"/> <lambda offset="7" closure="0"/> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="7" startColumn="5" endLine="7" endColumn="72" document="1"/> <entry offset="0x1" hidden="true" document="1"/> <entry offset="0xe" startLine="8" startColumn="9" endLine="10" endColumn="21" document="1"/> <entry offset="0x1d" startLine="11" startColumn="5" endLine="11" endColumn="17" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x1f"> <importsforward declaringType="Module1" methodName="Main"/> <local name="$VB$Closure_0" il_index="0" il_start="0x0" il_end="0x1f" attributes="0"/> <local name="MakeIncrementer" il_index="1" il_start="0x0" il_end="0x1f" attributes="0"/> </scope> </method> </methods> </symbols>) End Sub ''' <summary> ''' If a synthesized .ctor contains user code (field initializers), ''' the method must have a sequence point at ''' offset 0 for correct stepping behavior. ''' </summary> <WorkItem(804681, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/804681")> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub DefaultConstructorWithInitializer() Dim source = <compilation> <file><![CDATA[ Class C Private o As Object = New Object() End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) compilation.VerifyPdb("C..ctor", <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="C" name=".ctor"> <sequencePoints> <entry offset="0x0" hidden="true" document="1"/> <entry offset="0x7" startLine="2" startColumn="13" endLine="2" endColumn="39" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x18"> <currentnamespace name=""/> </scope> </method> </methods> </symbols>) End Sub ''' <summary> ''' If a synthesized method contains any user code, ''' the method must have a sequence point at ''' offset 0 for correct stepping behavior. ''' </summary> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub SequencePointAtOffset0() Dim source = <compilation> <file><![CDATA[ Imports System Module M Private Fn As Func(Of Object, Integer) = Function(x) Dim f As Func(Of Object, Integer) = Function(o) 1 Dim g As Func(Of Func(Of Object, Integer), Func(Of Object, Integer)) = Function(h) Function(y) h(y) Return g(f)(Nothing) End Function End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugDll) compilation.VerifyPdb( <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="M" name=".cctor"> <customDebugInfo> <encLambdaMap> <methodOrdinal>0</methodOrdinal> <closure offset="-84"/> <lambda offset="-243"/> <lambda offset="-182"/> <lambda offset="-84"/> <lambda offset="-72" closure="0"/> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="3" startColumn="13" endLine="7" endColumn="21" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x16"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> </scope> </method> <method containingType="M+_Closure$__0-0" name="_Lambda$__3" parameterNames="y"> <customDebugInfo> <encLocalSlotMap> <slot kind="21" offset="-72"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="5" startColumn="96" endLine="5" endColumn="107" document="1"/> <entry offset="0x1" startLine="5" startColumn="108" endLine="5" endColumn="112" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x17"> <importsforward declaringType="M" methodName=".cctor"/> </scope> </method> <method containingType="M+_Closure$__" name="_Lambda$__0-0" parameterNames="x"> <customDebugInfo> <encLocalSlotMap> <slot kind="21" offset="-243"/> <slot kind="0" offset="-214"/> <slot kind="0" offset="-151"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="3" startColumn="46" endLine="3" endColumn="57" document="1"/> <entry offset="0x1" startLine="4" startColumn="17" endLine="4" endColumn="62" document="1"/> <entry offset="0x26" startLine="5" startColumn="17" endLine="5" endColumn="112" document="1"/> <entry offset="0x4b" startLine="6" startColumn="13" endLine="6" endColumn="33" document="1"/> <entry offset="0x5b" startLine="7" startColumn="9" endLine="7" endColumn="21" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x5d"> <importsforward declaringType="M" methodName=".cctor"/> <local name="f" il_index="1" il_start="0x0" il_end="0x5d" attributes="0"/> <local name="g" il_index="2" il_start="0x0" il_end="0x5d" attributes="0"/> </scope> </method> <method containingType="M+_Closure$__" name="_Lambda$__0-1" parameterNames="o"> <customDebugInfo> <encLocalSlotMap> <slot kind="21" offset="-182"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="4" startColumn="49" endLine="4" endColumn="60" document="1"/> <entry offset="0x1" startLine="4" startColumn="61" endLine="4" endColumn="62" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x7"> <importsforward declaringType="M" methodName=".cctor"/> </scope> </method> <method containingType="M+_Closure$__" name="_Lambda$__0-2" parameterNames="h"> <customDebugInfo> <encLocalSlotMap> <slot kind="30" offset="-84"/> <slot kind="21" offset="-84"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="5" startColumn="84" endLine="5" endColumn="95" document="1"/> <entry offset="0x1" hidden="true" document="1"/> <entry offset="0xe" startLine="5" startColumn="96" endLine="5" endColumn="112" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x1f"> <importsforward declaringType="M" methodName=".cctor"/> <local name="$VB$Closure_0" il_index="0" il_start="0x0" il_end="0x1f" attributes="0"/> </scope> </method> </methods> </symbols>) End Sub <WorkItem(846228, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/846228")> <WorkItem(845078, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/845078")> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub RaiseEvent001() Dim source = <compilation> <file><![CDATA[ Public Class IntervalUpdate Public Shared Sub Update() RaiseEvent IntervalElapsed() End Sub Shared Sub Main() Update() End Sub Public Shared Event IntervalElapsed() End Class ]]></file> </compilation> Dim defines = PredefinedPreprocessorSymbols.AddPredefinedPreprocessorSymbols(OutputKind.ConsoleApplication) defines = defines.Add(KeyValuePairUtil.Create("_MyType", CObj("Console"))) Dim parseOptions = New VisualBasicParseOptions(preprocessorSymbols:=defines) Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugDll.WithParseOptions(parseOptions)) CompileAndVerify(compilation).VerifyIL("IntervalUpdate.Update", " { // Code size 18 (0x12) .maxstack 1 .locals init (IntervalUpdate.IntervalElapsedEventHandler V_0) -IL_0000: nop -IL_0001: ldsfld ""IntervalUpdate.IntervalElapsedEvent As IntervalUpdate.IntervalElapsedEventHandler"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0011 IL_000a: ldloc.0 IL_000b: callvirt ""Sub IntervalUpdate.IntervalElapsedEventHandler.Invoke()"" IL_0010: nop -IL_0011: ret } ", sequencePoints:="IntervalUpdate.Update") compilation.VerifyPdb( <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="My.MyComputer" name=".ctor"> <sequencePoints> <entry offset="0x0" startLine="109" startColumn="9" endLine="109" endColumn="25" document="1"/> <entry offset="0x1" startLine="110" startColumn="13" endLine="110" endColumn="25" document="1"/> <entry offset="0x8" startLine="111" startColumn="9" endLine="111" endColumn="16" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x9"> <currentnamespace name="My"/> </scope> </method> <method containingType="My.MyProject" name=".cctor"> <sequencePoints> <entry offset="0x0" startLine="128" startColumn="26" endLine="128" endColumn="97" document="1"/> <entry offset="0xa" startLine="139" startColumn="26" endLine="139" endColumn="95" document="1"/> <entry offset="0x14" startLine="150" startColumn="26" endLine="150" endColumn="136" document="1"/> <entry offset="0x1e" startLine="286" startColumn="26" endLine="286" endColumn="105" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x29"> <importsforward declaringType="My.MyComputer" methodName=".ctor"/> </scope> </method> <method containingType="My.MyProject" name="get_Computer"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="123" startColumn="13" endLine="123" endColumn="16" document="1"/> <entry offset="0x1" startLine="124" startColumn="17" endLine="124" endColumn="62" document="1"/> <entry offset="0xe" startLine="125" startColumn="13" endLine="125" endColumn="20" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x10"> <importsforward declaringType="My.MyComputer" methodName=".ctor"/> <local name="Computer" il_index="0" il_start="0x0" il_end="0x10" attributes="0"/> </scope> </method> <method containingType="My.MyProject" name="get_Application"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="135" startColumn="13" endLine="135" endColumn="16" document="1"/> <entry offset="0x1" startLine="136" startColumn="17" endLine="136" endColumn="57" document="1"/> <entry offset="0xe" startLine="137" startColumn="13" endLine="137" endColumn="20" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x10"> <importsforward declaringType="My.MyComputer" methodName=".ctor"/> <local name="Application" il_index="0" il_start="0x0" il_end="0x10" attributes="0"/> </scope> </method> <method containingType="My.MyProject" name="get_User"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="146" startColumn="13" endLine="146" endColumn="16" document="1"/> <entry offset="0x1" startLine="147" startColumn="17" endLine="147" endColumn="58" document="1"/> <entry offset="0xe" startLine="148" startColumn="13" endLine="148" endColumn="20" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x10"> <importsforward declaringType="My.MyComputer" methodName=".ctor"/> <local name="User" il_index="0" il_start="0x0" il_end="0x10" attributes="0"/> </scope> </method> <method containingType="My.MyProject" name="get_WebServices"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="239" startColumn="14" endLine="239" endColumn="17" document="1"/> <entry offset="0x1" startLine="240" startColumn="17" endLine="240" endColumn="67" document="1"/> <entry offset="0xe" startLine="241" startColumn="13" endLine="241" endColumn="20" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x10"> <importsforward declaringType="My.MyComputer" methodName=".ctor"/> <local name="WebServices" il_index="0" il_start="0x0" il_end="0x10" attributes="0"/> </scope> </method> <method containingType="IntervalUpdate" name="Update"> <sequencePoints> <entry offset="0x0" startLine="2" startColumn="5" endLine="2" endColumn="31" document="1"/> <entry offset="0x1" startLine="3" startColumn="9" endLine="3" endColumn="37" document="1"/> <entry offset="0x11" startLine="4" startColumn="5" endLine="4" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x12"> <currentnamespace name=""/> </scope> </method> <method containingType="IntervalUpdate" name="Main"> <sequencePoints> <entry offset="0x0" startLine="6" startColumn="5" endLine="6" endColumn="22" document="1"/> <entry offset="0x1" startLine="7" startColumn="9" endLine="7" endColumn="17" document="1"/> <entry offset="0x7" startLine="8" startColumn="5" endLine="8" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x8"> <importsforward declaringType="IntervalUpdate" methodName="Update"/> </scope> </method> <method containingType="My.MyProject+MyWebServices" name="Equals" parameterNames="o"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="249" startColumn="13" endLine="249" endColumn="75" document="1"/> <entry offset="0x1" startLine="250" startColumn="17" endLine="250" endColumn="40" document="1"/> <entry offset="0x10" startLine="251" startColumn="13" endLine="251" endColumn="25" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x12"> <currentnamespace name="My"/> <local name="Equals" il_index="0" il_start="0x0" il_end="0x12" attributes="0"/> </scope> </method> <method containingType="My.MyProject+MyWebServices" name="GetHashCode"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="253" startColumn="13" endLine="253" endColumn="63" document="1"/> <entry offset="0x1" startLine="254" startColumn="17" endLine="254" endColumn="42" document="1"/> <entry offset="0xa" startLine="255" startColumn="13" endLine="255" endColumn="25" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0xc"> <importsforward declaringType="My.MyProject+MyWebServices" methodName="Equals" parameterNames="o"/> <local name="GetHashCode" il_index="0" il_start="0x0" il_end="0xc" attributes="0"/> </scope> </method> <method containingType="My.MyProject+MyWebServices" name="GetType"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="257" startColumn="13" endLine="257" endColumn="72" document="1"/> <entry offset="0x1" startLine="258" startColumn="17" endLine="258" endColumn="46" document="1"/> <entry offset="0xe" startLine="259" startColumn="13" endLine="259" endColumn="25" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x10"> <importsforward declaringType="My.MyProject+MyWebServices" methodName="Equals" parameterNames="o"/> <local name="GetType" il_index="0" il_start="0x0" il_end="0x10" attributes="0"/> </scope> </method> <method containingType="My.MyProject+MyWebServices" name="ToString"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="261" startColumn="13" endLine="261" endColumn="59" document="1"/> <entry offset="0x1" startLine="262" startColumn="17" endLine="262" endColumn="39" document="1"/> <entry offset="0xa" startLine="263" startColumn="13" endLine="263" endColumn="25" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0xc"> <importsforward declaringType="My.MyProject+MyWebServices" methodName="Equals" parameterNames="o"/> <local name="ToString" il_index="0" il_start="0x0" il_end="0xc" attributes="0"/> </scope> </method> <method containingType="My.MyProject+MyWebServices" name="Create__Instance__" parameterNames="instance"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> <slot kind="1" offset="0"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="266" startColumn="12" endLine="266" endColumn="95" document="1"/> <entry offset="0x1" startLine="267" startColumn="17" endLine="267" endColumn="44" document="1"/> <entry offset="0xb" hidden="true" document="1"/> <entry offset="0xe" startLine="268" startColumn="21" endLine="268" endColumn="35" document="1"/> <entry offset="0x16" startLine="269" startColumn="17" endLine="269" endColumn="21" document="1"/> <entry offset="0x17" startLine="270" startColumn="21" endLine="270" endColumn="36" document="1"/> <entry offset="0x1b" startLine="272" startColumn="13" endLine="272" endColumn="25" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x1d"> <importsforward declaringType="My.MyProject+MyWebServices" methodName="Equals" parameterNames="o"/> <local name="Create__Instance__" il_index="0" il_start="0x0" il_end="0x1d" attributes="0"/> </scope> </method> <method containingType="My.MyProject+MyWebServices" name="Dispose__Instance__" parameterNames="instance"> <sequencePoints> <entry offset="0x0" startLine="275" startColumn="13" endLine="275" endColumn="71" document="1"/> <entry offset="0x1" startLine="276" startColumn="17" endLine="276" endColumn="35" document="1"/> <entry offset="0x8" startLine="277" startColumn="13" endLine="277" endColumn="20" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x9"> <importsforward declaringType="My.MyProject+MyWebServices" methodName="Equals" parameterNames="o"/> </scope> </method> <method containingType="My.MyProject+MyWebServices" name=".ctor"> <sequencePoints> <entry offset="0x0" startLine="281" startColumn="13" endLine="281" endColumn="29" document="1"/> <entry offset="0x1" startLine="282" startColumn="16" endLine="282" endColumn="28" document="1"/> <entry offset="0x8" startLine="283" startColumn="13" endLine="283" endColumn="20" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x9"> <importsforward declaringType="My.MyProject+MyWebServices" methodName="Equals" parameterNames="o"/> </scope> </method> <method containingType="My.MyProject+ThreadSafeObjectProvider`1" name="get_GetInstance"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> <slot kind="1" offset="0"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="343" startColumn="17" endLine="343" endColumn="20" document="1"/> <entry offset="0x1" startLine="344" startColumn="21" endLine="344" endColumn="59" document="1"/> <entry offset="0xf" hidden="true" document="1"/> <entry offset="0x12" startLine="344" startColumn="60" endLine="344" endColumn="87" document="1"/> <entry offset="0x1c" startLine="345" startColumn="21" endLine="345" endColumn="47" document="1"/> <entry offset="0x24" startLine="346" startColumn="17" endLine="346" endColumn="24" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x26"> <importsforward declaringType="My.MyProject+MyWebServices" methodName="Equals" parameterNames="o"/> <local name="GetInstance" il_index="0" il_start="0x0" il_end="0x26" attributes="0"/> </scope> </method> <method containingType="My.MyProject+ThreadSafeObjectProvider`1" name=".ctor"> <sequencePoints> <entry offset="0x0" startLine="352" startColumn="13" endLine="352" endColumn="29" document="1"/> <entry offset="0x1" startLine="353" startColumn="17" endLine="353" endColumn="29" document="1"/> <entry offset="0x8" startLine="354" startColumn="13" endLine="354" endColumn="20" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x9"> <importsforward declaringType="My.MyProject+MyWebServices" methodName="Equals" parameterNames="o"/> </scope> </method> </methods> </symbols>, options:=PdbValidationOptions.SkipConversionValidation) ' TODO: https://github.com/dotnet/roslyn/issues/18004 End Sub <WorkItem(876518, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/876518")> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub WinFormMain() Dim source = <compilation> <file> &lt;Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()&gt; _ Partial Class Form1 Inherits System.Windows.Forms.Form 'Form overrides dispose to clean up the component list. &lt;System.Diagnostics.DebuggerNonUserCode()&gt; _ Protected Overrides Sub Dispose(ByVal disposing As Boolean) Try If disposing AndAlso components IsNot Nothing Then components.Dispose() End If Finally MyBase.Dispose(disposing) End Try End Sub 'Required by the Windows Form Designer Private components As System.ComponentModel.IContainer 'NOTE: The following procedure is required by the Windows Form Designer 'It can be modified using the Windows Form Designer. 'Do not modify it using the code editor. &lt;System.Diagnostics.DebuggerStepThrough()&gt; _ Private Sub InitializeComponent() components = New System.ComponentModel.Container() Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font Me.Text = "Form1" End Sub End Class </file> </compilation> Dim defines = PredefinedPreprocessorSymbols.AddPredefinedPreprocessorSymbols( OutputKind.WindowsApplication, KeyValuePairUtil.Create(Of String, Object)("_MyType", "WindowsForms"), KeyValuePairUtil.Create(Of String, Object)("Config", "Debug"), KeyValuePairUtil.Create(Of String, Object)("DEBUG", -1), KeyValuePairUtil.Create(Of String, Object)("TRACE", -1), KeyValuePairUtil.Create(Of String, Object)("PLATFORM", "AnyCPU")) Dim parseOptions As VisualBasicParseOptions = New VisualBasicParseOptions(preprocessorSymbols:=defines) Dim compOptions As VisualBasicCompilationOptions = New VisualBasicCompilationOptions( OutputKind.WindowsApplication, optimizationLevel:=OptimizationLevel.Debug, parseOptions:=parseOptions, mainTypeName:="My.MyApplication") Dim comp = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, {SystemWindowsFormsRef}, compOptions) comp.VerifyDiagnostics() ' Just care that there's at least one non-hidden sequence point. comp.VerifyPdb("My.MyApplication.Main", <symbols> <files> <file id="1" name="" language="VB"/> </files> <entryPoint declaringType="My.MyApplication" methodName="Main" parameterNames="Args"/> <methods> <method containingType="My.MyApplication" name="Main" parameterNames="Args"> <sequencePoints> <entry offset="0x0" startLine="78" startColumn="9" endLine="78" endColumn="55" document="1"/> <entry offset="0x1" startLine="79" startColumn="13" endLine="79" endColumn="16" document="1"/> <entry offset="0x2" startLine="80" startColumn="16" endLine="80" endColumn="133" document="1"/> <entry offset="0xf" startLine="81" startColumn="13" endLine="81" endColumn="20" document="1"/> <entry offset="0x11" startLine="82" startColumn="13" endLine="82" endColumn="20" document="1"/> <entry offset="0x12" startLine="83" startColumn="13" endLine="83" endColumn="37" document="1"/> <entry offset="0x1e" startLine="84" startColumn="9" endLine="84" endColumn="16" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x1f"> <currentnamespace name="My"/> </scope> </method> </methods> </symbols>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub SynthesizedVariableForSelectCastValue() Dim source = <compilation> <file> Imports System Class C Sub F(args As String()) Select Case args(0) Case "a" Console.WriteLine(1) Case "b" Console.WriteLine(2) Case "c" Console.WriteLine(3) End Select End Sub End Class </file> </compilation> Dim c = CreateCompilationWithMscorlib40AndVBRuntime(source, options:=TestOptions.DebugDll) c.VerifyDiagnostics() c.VerifyPdb("C.F", <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="C" name="F" parameterNames="args"> <customDebugInfo> <encLocalSlotMap> <slot kind="15" offset="0"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="3" startColumn="5" endLine="3" endColumn="28" document="1"/> <entry offset="0x1" startLine="4" startColumn="9" endLine="4" endColumn="28" document="1"/> <entry offset="0x32" startLine="5" startColumn="13" endLine="5" endColumn="21" document="1"/> <entry offset="0x33" startLine="6" startColumn="17" endLine="6" endColumn="37" document="1"/> <entry offset="0x3c" startLine="7" startColumn="13" endLine="7" endColumn="21" document="1"/> <entry offset="0x3d" startLine="8" startColumn="17" endLine="8" endColumn="37" document="1"/> <entry offset="0x46" startLine="9" startColumn="13" endLine="9" endColumn="21" document="1"/> <entry offset="0x47" startLine="10" startColumn="17" endLine="10" endColumn="37" document="1"/> <entry offset="0x50" startLine="11" startColumn="9" endLine="11" endColumn="19" document="1"/> <entry offset="0x51" startLine="12" startColumn="5" endLine="12" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x52"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> </scope> </method> </methods> </symbols>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub Constant_AllTypes() Dim source = <compilation> <file> Imports System Imports System.Collections.Generic 'Imports Microsoft.VisualBasic.Strings Class X End Class Public Class C(Of S) Enum EnumI1 As SByte : A : End Enum Enum EnumU1 As Byte : A : End Enum Enum EnumI2 As Short : A : End Enum Enum EnumU2 As UShort : A : End Enum Enum EnumI4 As Integer : A : End Enum Enum EnumU4 As UInteger : A : End Enum Enum EnumI8 As Long : A : End Enum Enum EnumU8 As ULong : A : End Enum Public Sub F(Of T)() Const B As Boolean = Nothing Const C As Char = Nothing Const I1 As SByte = 0 Const U1 As Byte = 0 Const I2 As Short = 0 Const U2 As UShort = 0 Const I4 As Integer = 0 Const U4 As UInteger = 0 Const I8 As Long = 0 Const U8 As ULong = 0 Const R4 As Single = 0 Const R8 As Double = 0 Const EI1 As C(Of Integer).EnumI1 = 0 Const EU1 As C(Of Integer).EnumU1 = 0 Const EI2 As C(Of Integer).EnumI2 = 0 Const EU2 As C(Of Integer).EnumU2 = 0 Const EI4 As C(Of Integer).EnumI4 = 0 Const EU4 As C(Of Integer).EnumU4 = 0 Const EI8 As C(Of Integer).EnumI8 = 0 Const EU8 As C(Of Integer).EnumU8 = 0 'Const StrWithNul As String = ChrW(0) Const EmptyStr As String = "" Const NullStr As String = Nothing Const NullObject As Object = Nothing Const D As Decimal = Nothing Const DT As DateTime = #1-1-2015# End Sub End Class </file> </compilation> Dim c = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, {SystemCoreRef}, options:=TestOptions.DebugDll.WithEmbedVbCoreRuntime(True)) c.VerifyPdb("C`1.F", <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="C`1" name="F"> <sequencePoints> <entry offset="0x0" startLine="18" startColumn="5" endLine="18" endColumn="25" document="1"/> <entry offset="0x1" startLine="48" startColumn="5" endLine="48" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x2"> <namespace name="System" importlevel="file"/> <namespace name="System.Collections.Generic" importlevel="file"/> <currentnamespace name=""/> <constant name="B" value="0" type="Boolean"/> <constant name="C" value="0" type="Char"/> <constant name="I1" value="0" type="SByte"/> <constant name="U1" value="0" type="Byte"/> <constant name="I2" value="0" type="Int16"/> <constant name="U2" value="0" type="UInt16"/> <constant name="I4" value="0" type="Int32"/> <constant name="U4" value="0" type="UInt32"/> <constant name="I8" value="0" type="Int64"/> <constant name="U8" value="0" type="UInt64"/> <constant name="R4" value="0x00000000" type="Single"/> <constant name="R8" value="0x0000000000000000" type="Double"/> <constant name="EI1" value="0" signature="EnumI1{Int32}"/> <constant name="EU1" value="0" signature="EnumU1{Int32}"/> <constant name="EI2" value="0" signature="EnumI2{Int32}"/> <constant name="EU2" value="0" signature="EnumU2{Int32}"/> <constant name="EI4" value="0" signature="EnumI4{Int32}"/> <constant name="EU4" value="0" signature="EnumU4{Int32}"/> <constant name="EI8" value="0" signature="EnumI8{Int32}"/> <constant name="EU8" value="0" signature="EnumU8{Int32}"/> <constant name="EmptyStr" value="" type="String"/> <constant name="NullStr" value="null" type="String"/> <constant name="NullObject" value="null" type="Object"/> <constant name="D" value="0" type="Decimal"/> <constant name="DT" value="01/01/2015 00:00:00" type="DateTime"/> </scope> </method> </methods> </symbols>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub ImportsInAsync() Dim source = "Imports System.Linq Imports System.Threading.Tasks Class C Shared Async Function F() As Task Dim c = {1, 2, 3} c.Select(Function(i) i) End Function End Class" Dim c = CreateCompilationWithMscorlib45AndVBRuntime({Parse(source)}, options:=TestOptions.DebugDll, references:={SystemCoreRef}) c.VerifyPdb("C+VB$StateMachine_1_F.MoveNext", <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="C+VB$StateMachine_1_F" name="MoveNext"> <customDebugInfo> <hoistedLocalScopes format="portable"> <slot startOffset="0x0" endOffset="0x8b"/> </hoistedLocalScopes> <encLocalSlotMap> <slot kind="27" offset="-1"/> <slot kind="temp"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" hidden="true" document="1"/> <entry offset="0x7" startLine="4" startColumn="5" endLine="4" endColumn="38" document="1"/> <entry offset="0x8" startLine="5" startColumn="13" endLine="5" endColumn="26" document="1"/> <entry offset="0x1f" startLine="6" startColumn="9" endLine="6" endColumn="32" document="1"/> <entry offset="0x4f" startLine="7" startColumn="5" endLine="7" endColumn="17" document="1"/> <entry offset="0x51" hidden="true" document="1"/> <entry offset="0x58" hidden="true" document="1"/> <entry offset="0x74" startLine="7" startColumn="5" endLine="7" endColumn="17" document="1"/> <entry offset="0x7e" hidden="true" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x8b"> <importsforward declaringType="C+_Closure$__" methodName="_Lambda$__1-0" parameterNames="i"/> <local name="$VB$ResumableLocal_c$0" il_index="0" il_start="0x0" il_end="0x8b" attributes="0"/> </scope> <asyncInfo> <kickoffMethod declaringType="C" methodName="F"/> </asyncInfo> </method> </methods> </symbols>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub ImportsInAsyncLambda() Dim source = "Imports System.Linq Class C Shared Sub M() Dim f As System.Action = Async Sub() Dim c = {1, 2, 3} c.Select(Function(i) i) End Sub End Sub End Class" Dim c = CreateCompilationWithMscorlib45AndVBRuntime({Parse(source)}, options:=TestOptions.DebugDll, references:={SystemCoreRef}) c.VerifyPdb("C+_Closure$__+VB$StateMachine___Lambda$__1-0.MoveNext", <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="C+_Closure$__+VB$StateMachine___Lambda$__1-0" name="MoveNext"> <customDebugInfo> <hoistedLocalScopes format="portable"> <slot startOffset="0x0" endOffset="0x8b"/> </hoistedLocalScopes> <encLocalSlotMap> <slot kind="27" offset="38"/> <slot kind="temp"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" hidden="true" document="1"/> <entry offset="0x7" startLine="5" startColumn="13" endLine="5" endColumn="24" document="1"/> <entry offset="0x8" startLine="6" startColumn="21" endLine="6" endColumn="34" document="1"/> <entry offset="0x1f" startLine="7" startColumn="17" endLine="7" endColumn="40" document="1"/> <entry offset="0x4f" startLine="8" startColumn="13" endLine="8" endColumn="20" document="1"/> <entry offset="0x51" hidden="true" document="1"/> <entry offset="0x58" hidden="true" document="1"/> <entry offset="0x74" hidden="true" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x8b"> <importsforward declaringType="C" methodName="M"/> <local name="$VB$ResumableLocal_c$0" il_index="0" il_start="0x0" il_end="0x8b" attributes="0"/> </scope> <asyncInfo> <catchHandler offset="0x51"/> <kickoffMethod declaringType="C+_Closure$__" methodName="_Lambda$__1-0"/> </asyncInfo> </method> </methods> </symbols>) End Sub <ConditionalFact(GetType(WindowsDesktopOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> <WorkItem(23525, "https://github.com/dotnet/roslyn/issues/23525")> Public Sub InvalidCharacterInPdbPath() Using outStream = Temp.CreateFile().Open() Dim Compilation = CreateEmptyCompilation("") Dim result = Compilation.Emit(outStream, options:=New EmitOptions(pdbFilePath:="test\\?.pdb", debugInformationFormat:=DebugInformationFormat.Embedded)) ' This is fine because EmitOptions just controls what is written into the PE file and it's ' valid for this to be an illegal file name (path map can easily create these). Assert.True(result.Success) End Using End Sub <ConditionalFact(GetType(WindowsDesktopOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> <WorkItem(38954, "https://github.com/dotnet/roslyn/issues/38954")> Public Sub FilesOneWithNoMethodBody() Dim source1 = "Imports System Class C Public Shared Sub Main() Console.WriteLine() End Sub End Class " Dim source2 = " ' no code " Dim tree1 = Parse(source1, "f:/build/goo.vb") Dim tree2 = Parse(source2, "f:/build/nocode.vb") Dim c = CreateCompilation({tree1, tree2}, options:=TestOptions.DebugDll) c.VerifyPdb(" <symbols> <files> <file id=""1"" name=""f:/build/goo.vb"" language=""VB"" checksumAlgorithm=""SHA1"" checksum=""48-27-3C-50-9D-24-D4-0D-51-87-6C-E2-FB-2F-AA-1C-80-96-0B-B7"" /> <file id=""2"" name=""f:/build/nocode.vb"" language=""VB"" checksumAlgorithm=""SHA1"" checksum=""40-43-2C-44-BA-1C-C7-1A-B3-F3-68-E5-96-7C-65-9D-61-85-D5-44"" /> </files> <methods> <method containingType=""C"" name=""Main""> <sequencePoints> <entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""29"" document=""1"" /> <entry offset=""0x1"" startLine=""5"" startColumn=""9"" endLine=""5"" endColumn=""28"" document=""1"" /> <entry offset=""0x7"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""12"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x8""> <namespace name=""System"" importlevel=""file"" /> <currentnamespace name="""" /> </scope> </method> </methods> </symbols> ") End Sub <ConditionalFact(GetType(WindowsDesktopOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> <WorkItem(38954, "https://github.com/dotnet/roslyn/issues/38954")> Public Sub SingleFileWithNoMethodBody() Dim source = " ' no code " Dim tree = Parse(source, "f:/build/nocode.vb") Dim c = CreateCompilation({tree}, options:=TestOptions.DebugDll) c.VerifyPdb(" <symbols> <files> <file id=""1"" name=""f:/build/nocode.vb"" language=""VB"" checksumAlgorithm=""SHA1"" checksum=""40-43-2C-44-BA-1C-C7-1A-B3-F3-68-E5-96-7C-65-9D-61-85-D5-44"" /> </files> <methods /> </symbols> ") End Sub End Class End Namespace
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/Compilers/Core/Portable/Symbols/ISourceAssemblySymbolInternal.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Reflection; namespace Microsoft.CodeAnalysis.Symbols { internal interface ISourceAssemblySymbolInternal : IAssemblySymbolInternal { AssemblyFlags AssemblyFlags { get; } /// <summary> /// The contents of the AssemblySignatureKeyAttribute /// </summary> string? SignatureKey { get; } AssemblyHashAlgorithm HashAlgorithm { get; } bool InternalsAreVisible { get; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Reflection; namespace Microsoft.CodeAnalysis.Symbols { internal interface ISourceAssemblySymbolInternal : IAssemblySymbolInternal { AssemblyFlags AssemblyFlags { get; } /// <summary> /// The contents of the AssemblySignatureKeyAttribute /// </summary> string? SignatureKey { get; } AssemblyHashAlgorithm HashAlgorithm { get; } bool InternalsAreVisible { get; } } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/VisualStudio/Core/Def/Implementation/Library/ObjectBrowser/AbstractObjectBrowserLibraryManager_ListItems.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Threading; using Microsoft.CodeAnalysis; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser { internal abstract partial class AbstractObjectBrowserLibraryManager { internal void CollectMemberListItems(IAssemblySymbol assemblySymbol, Compilation compilation, ProjectId projectId, ImmutableArray<ObjectListItem>.Builder builder, string searchString) => GetListItemFactory().CollectMemberListItems(assemblySymbol, compilation, projectId, builder, searchString); internal void CollectNamespaceListItems(IAssemblySymbol assemblySymbol, ProjectId projectId, ImmutableArray<ObjectListItem>.Builder builder, string searchString) => GetListItemFactory().CollectNamespaceListItems(assemblySymbol, projectId, builder, searchString); internal void CollectTypeListItems(IAssemblySymbol assemblySymbol, Compilation compilation, ProjectId projectId, ImmutableArray<ObjectListItem>.Builder builder, string searchString) => GetListItemFactory().CollectTypeListItems(assemblySymbol, compilation, projectId, builder, searchString); internal ImmutableHashSet<Tuple<ProjectId, IAssemblySymbol>> GetAssemblySet(Solution solution, string languageName, CancellationToken cancellationToken) => GetListItemFactory().GetAssemblySet(solution, languageName, cancellationToken); internal ImmutableHashSet<Tuple<ProjectId, IAssemblySymbol>> GetAssemblySet(Project project, bool lookInReferences, CancellationToken cancellationToken) => GetListItemFactory().GetAssemblySet(project, lookInReferences, cancellationToken); internal ImmutableArray<ObjectListItem> GetBaseTypeListItems(ObjectListItem parentListItem, Compilation compilation) => GetListItemFactory().GetBaseTypeListItems(parentListItem, compilation); internal ImmutableArray<ObjectListItem> GetFolderListItems(ObjectListItem parentListItem, Compilation compilation) => GetListItemFactory().GetFolderListItems(parentListItem, compilation); internal ImmutableArray<ObjectListItem> GetMemberListItems(ObjectListItem parentListItem, Compilation compilation) => GetListItemFactory().GetMemberListItems(parentListItem, compilation); internal ImmutableArray<ObjectListItem> GetNamespaceListItems(ObjectListItem parentListItem, Compilation compilation) => GetListItemFactory().GetNamespaceListItems(parentListItem, compilation); internal ImmutableArray<ObjectListItem> GetProjectListItems(Solution solution, string languageName, uint listFlags) => GetListItemFactory().GetProjectListItems(solution, languageName, listFlags); internal ImmutableArray<ObjectListItem> GetReferenceListItems(ObjectListItem parentListItem, Compilation compilation) => GetListItemFactory().GetReferenceListItems(parentListItem, compilation); internal ImmutableArray<ObjectListItem> GetTypeListItems(ObjectListItem parentListItem, Compilation compilation) => GetListItemFactory().GetTypeListItems(parentListItem, compilation); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Threading; using Microsoft.CodeAnalysis; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser { internal abstract partial class AbstractObjectBrowserLibraryManager { internal void CollectMemberListItems(IAssemblySymbol assemblySymbol, Compilation compilation, ProjectId projectId, ImmutableArray<ObjectListItem>.Builder builder, string searchString) => GetListItemFactory().CollectMemberListItems(assemblySymbol, compilation, projectId, builder, searchString); internal void CollectNamespaceListItems(IAssemblySymbol assemblySymbol, ProjectId projectId, ImmutableArray<ObjectListItem>.Builder builder, string searchString) => GetListItemFactory().CollectNamespaceListItems(assemblySymbol, projectId, builder, searchString); internal void CollectTypeListItems(IAssemblySymbol assemblySymbol, Compilation compilation, ProjectId projectId, ImmutableArray<ObjectListItem>.Builder builder, string searchString) => GetListItemFactory().CollectTypeListItems(assemblySymbol, compilation, projectId, builder, searchString); internal ImmutableHashSet<Tuple<ProjectId, IAssemblySymbol>> GetAssemblySet(Solution solution, string languageName, CancellationToken cancellationToken) => GetListItemFactory().GetAssemblySet(solution, languageName, cancellationToken); internal ImmutableHashSet<Tuple<ProjectId, IAssemblySymbol>> GetAssemblySet(Project project, bool lookInReferences, CancellationToken cancellationToken) => GetListItemFactory().GetAssemblySet(project, lookInReferences, cancellationToken); internal ImmutableArray<ObjectListItem> GetBaseTypeListItems(ObjectListItem parentListItem, Compilation compilation) => GetListItemFactory().GetBaseTypeListItems(parentListItem, compilation); internal ImmutableArray<ObjectListItem> GetFolderListItems(ObjectListItem parentListItem, Compilation compilation) => GetListItemFactory().GetFolderListItems(parentListItem, compilation); internal ImmutableArray<ObjectListItem> GetMemberListItems(ObjectListItem parentListItem, Compilation compilation) => GetListItemFactory().GetMemberListItems(parentListItem, compilation); internal ImmutableArray<ObjectListItem> GetNamespaceListItems(ObjectListItem parentListItem, Compilation compilation) => GetListItemFactory().GetNamespaceListItems(parentListItem, compilation); internal ImmutableArray<ObjectListItem> GetProjectListItems(Solution solution, string languageName, uint listFlags) => GetListItemFactory().GetProjectListItems(solution, languageName, listFlags); internal ImmutableArray<ObjectListItem> GetReferenceListItems(ObjectListItem parentListItem, Compilation compilation) => GetListItemFactory().GetReferenceListItems(parentListItem, compilation); internal ImmutableArray<ObjectListItem> GetTypeListItems(ObjectListItem parentListItem, Compilation compilation) => GetListItemFactory().GetTypeListItems(parentListItem, compilation); } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/VisualStudio/Core/Impl/CodeModel/InternalElements/CodeProperty.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements { [ComVisible(true)] [ComDefaultInterface(typeof(EnvDTE80.CodeProperty2))] public sealed partial class CodeProperty : AbstractCodeMember, ICodeElementContainer<CodeParameter>, ICodeElementContainer<CodeAttribute>, EnvDTE.CodeProperty, EnvDTE80.CodeProperty2 { internal static EnvDTE.CodeProperty Create( CodeModelState state, FileCodeModel fileCodeModel, SyntaxNodeKey nodeKey, int? nodeKind) { var element = new CodeProperty(state, fileCodeModel, nodeKey, nodeKind); var result = (EnvDTE.CodeProperty)ComAggregate.CreateAggregatedObject(element); fileCodeModel.OnCodeElementCreated(nodeKey, (EnvDTE.CodeElement)result); return result; } internal static EnvDTE.CodeProperty CreateUnknown( CodeModelState state, FileCodeModel fileCodeModel, int nodeKind, string name) { var element = new CodeProperty(state, fileCodeModel, nodeKind, name); return (EnvDTE.CodeProperty)ComAggregate.CreateAggregatedObject(element); } private CodeProperty( CodeModelState state, FileCodeModel fileCodeModel, SyntaxNodeKey nodeKey, int? nodeKind) : base(state, fileCodeModel, nodeKey, nodeKind) { } private CodeProperty( CodeModelState state, FileCodeModel fileCodeModel, int nodeKind, string name) : base(state, fileCodeModel, nodeKind, name) { } private IPropertySymbol PropertySymbol { get { return (IPropertySymbol)LookupSymbol(); } } EnvDTE.CodeElements ICodeElementContainer<CodeParameter>.GetCollection() => this.Parameters; EnvDTE.CodeElements ICodeElementContainer<CodeAttribute>.GetCollection() => this.Attributes; internal override ImmutableArray<SyntaxNode> GetParameters() => ImmutableArray.CreateRange(CodeModelService.GetParameterNodes(LookupNode())); protected override object GetExtenderNames() => CodeModelService.GetPropertyExtenderNames(); protected override object GetExtender(string name) => CodeModelService.GetPropertyExtender(name, LookupNode(), LookupSymbol()); public override EnvDTE.vsCMElement Kind { get { return EnvDTE.vsCMElement.vsCMElementProperty; } } public override object Parent { get { EnvDTE80.CodeProperty2 codeProperty = this; return codeProperty.Parent2; } } public EnvDTE.CodeElement Parent2 { get { var containingTypeNode = GetContainingTypeNode(); if (containingTypeNode == null) { throw Exceptions.ThrowEUnexpected(); } return FileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(containingTypeNode); } } EnvDTE.CodeClass EnvDTE.CodeProperty.Parent { get { if (this.Parent is EnvDTE.CodeClass parentClass) { return parentClass; } else { throw new InvalidOperationException(); } } } EnvDTE.CodeClass EnvDTE80.CodeProperty2.Parent { get { EnvDTE.CodeProperty property = this; return property.Parent; } } public override EnvDTE.CodeElements Children { get { return this.Attributes; } } private bool HasAccessorNode(MethodKind methodKind) => CodeModelService.TryGetAccessorNode(LookupNode(), methodKind, out _); private bool IsExpressionBodiedProperty() => CodeModelService.IsExpressionBodiedProperty(LookupNode()); public EnvDTE.CodeFunction Getter { get { if (!HasAccessorNode(MethodKind.PropertyGet) && !IsExpressionBodiedProperty()) { return null; } return CodeAccessorFunction.Create(this.State, this, MethodKind.PropertyGet); } set { throw Exceptions.ThrowENotImpl(); } } public EnvDTE.CodeFunction Setter { get { if (!HasAccessorNode(MethodKind.PropertySet)) { return null; } return CodeAccessorFunction.Create(this.State, this, MethodKind.PropertySet); } set { throw Exceptions.ThrowENotImpl(); } } public EnvDTE.CodeTypeRef Type { get { return CodeTypeRef.Create(this.State, this, GetProjectId(), PropertySymbol.Type); } set { // The type is sometimes part of the node key, so we should be sure to reacquire // it after updating it. Note that we pass trackKinds: false because it's possible // that UpdateType might change the kind of a node (e.g. change a VB Sub to a Function). UpdateNodeAndReacquireNodeKey(FileCodeModel.UpdateType, value, trackKinds: false); } } public bool IsDefault { get { return CodeModelService.GetIsDefault(LookupNode()); } set { UpdateNode(FileCodeModel.UpdateIsDefault, value); } } public EnvDTE80.vsCMPropertyKind ReadWrite { get { return CodeModelService.GetReadWrite(LookupNode()); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements { [ComVisible(true)] [ComDefaultInterface(typeof(EnvDTE80.CodeProperty2))] public sealed partial class CodeProperty : AbstractCodeMember, ICodeElementContainer<CodeParameter>, ICodeElementContainer<CodeAttribute>, EnvDTE.CodeProperty, EnvDTE80.CodeProperty2 { internal static EnvDTE.CodeProperty Create( CodeModelState state, FileCodeModel fileCodeModel, SyntaxNodeKey nodeKey, int? nodeKind) { var element = new CodeProperty(state, fileCodeModel, nodeKey, nodeKind); var result = (EnvDTE.CodeProperty)ComAggregate.CreateAggregatedObject(element); fileCodeModel.OnCodeElementCreated(nodeKey, (EnvDTE.CodeElement)result); return result; } internal static EnvDTE.CodeProperty CreateUnknown( CodeModelState state, FileCodeModel fileCodeModel, int nodeKind, string name) { var element = new CodeProperty(state, fileCodeModel, nodeKind, name); return (EnvDTE.CodeProperty)ComAggregate.CreateAggregatedObject(element); } private CodeProperty( CodeModelState state, FileCodeModel fileCodeModel, SyntaxNodeKey nodeKey, int? nodeKind) : base(state, fileCodeModel, nodeKey, nodeKind) { } private CodeProperty( CodeModelState state, FileCodeModel fileCodeModel, int nodeKind, string name) : base(state, fileCodeModel, nodeKind, name) { } private IPropertySymbol PropertySymbol { get { return (IPropertySymbol)LookupSymbol(); } } EnvDTE.CodeElements ICodeElementContainer<CodeParameter>.GetCollection() => this.Parameters; EnvDTE.CodeElements ICodeElementContainer<CodeAttribute>.GetCollection() => this.Attributes; internal override ImmutableArray<SyntaxNode> GetParameters() => ImmutableArray.CreateRange(CodeModelService.GetParameterNodes(LookupNode())); protected override object GetExtenderNames() => CodeModelService.GetPropertyExtenderNames(); protected override object GetExtender(string name) => CodeModelService.GetPropertyExtender(name, LookupNode(), LookupSymbol()); public override EnvDTE.vsCMElement Kind { get { return EnvDTE.vsCMElement.vsCMElementProperty; } } public override object Parent { get { EnvDTE80.CodeProperty2 codeProperty = this; return codeProperty.Parent2; } } public EnvDTE.CodeElement Parent2 { get { var containingTypeNode = GetContainingTypeNode(); if (containingTypeNode == null) { throw Exceptions.ThrowEUnexpected(); } return FileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(containingTypeNode); } } EnvDTE.CodeClass EnvDTE.CodeProperty.Parent { get { if (this.Parent is EnvDTE.CodeClass parentClass) { return parentClass; } else { throw new InvalidOperationException(); } } } EnvDTE.CodeClass EnvDTE80.CodeProperty2.Parent { get { EnvDTE.CodeProperty property = this; return property.Parent; } } public override EnvDTE.CodeElements Children { get { return this.Attributes; } } private bool HasAccessorNode(MethodKind methodKind) => CodeModelService.TryGetAccessorNode(LookupNode(), methodKind, out _); private bool IsExpressionBodiedProperty() => CodeModelService.IsExpressionBodiedProperty(LookupNode()); public EnvDTE.CodeFunction Getter { get { if (!HasAccessorNode(MethodKind.PropertyGet) && !IsExpressionBodiedProperty()) { return null; } return CodeAccessorFunction.Create(this.State, this, MethodKind.PropertyGet); } set { throw Exceptions.ThrowENotImpl(); } } public EnvDTE.CodeFunction Setter { get { if (!HasAccessorNode(MethodKind.PropertySet)) { return null; } return CodeAccessorFunction.Create(this.State, this, MethodKind.PropertySet); } set { throw Exceptions.ThrowENotImpl(); } } public EnvDTE.CodeTypeRef Type { get { return CodeTypeRef.Create(this.State, this, GetProjectId(), PropertySymbol.Type); } set { // The type is sometimes part of the node key, so we should be sure to reacquire // it after updating it. Note that we pass trackKinds: false because it's possible // that UpdateType might change the kind of a node (e.g. change a VB Sub to a Function). UpdateNodeAndReacquireNodeKey(FileCodeModel.UpdateType, value, trackKinds: false); } } public bool IsDefault { get { return CodeModelService.GetIsDefault(LookupNode()); } set { UpdateNode(FileCodeModel.UpdateIsDefault, value); } } public EnvDTE80.vsCMPropertyKind ReadWrite { get { return CodeModelService.GetReadWrite(LookupNode()); } } } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/VisualStudio/Core/Impl/CodeModel/FileCodeModel.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Linq; using System.Runtime.InteropServices; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel { /// <summary> /// Implementations of EnvDTE.FileCodeModel for both languages. /// </summary> public sealed partial class FileCodeModel : AbstractCodeModelObject, EnvDTE.FileCodeModel, EnvDTE80.FileCodeModel2, ICodeElementContainer<AbstractCodeElement>, IVBFileCodeModelEvents, ICSCodeModelRefactoring { internal static ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel> Create( CodeModelState state, object parent, DocumentId documentId, ITextManagerAdapter textManagerAdapter) { return new FileCodeModel(state, parent, documentId, textManagerAdapter).GetComHandle<EnvDTE80.FileCodeModel2, FileCodeModel>(); } private readonly ComHandle<object, object> _parentHandle; /// <summary> /// Don't use directly. Instead, call <see cref="GetDocumentId()"/>. /// </summary> private DocumentId _documentId; // Note: these are only valid when the underlying file is being renamed. Do not use. private ProjectId _incomingProjectId; private string _incomingFilePath; private Document _previousDocument; private readonly CleanableWeakComHandleTable<SyntaxNodeKey, EnvDTE.CodeElement> _codeElementTable; // These are used during batching. private bool _batchMode; private List<AbstractKeyedCodeElement> _batchElements; private Document _batchDocument; // track state to make sure we open editor only once private int _editCount; private IInvisibleEditor _invisibleEditor; private SyntaxTree _lastSyntaxTree; private FileCodeModel( CodeModelState state, object parent, DocumentId documentId, ITextManagerAdapter textManagerAdapter) : base(state) { Debug.Assert(documentId != null); Debug.Assert(textManagerAdapter != null); _parentHandle = new ComHandle<object, object>(parent); _documentId = documentId; TextManagerAdapter = textManagerAdapter; _codeElementTable = new CleanableWeakComHandleTable<SyntaxNodeKey, EnvDTE.CodeElement>(state.ThreadingContext); _batchMode = false; _batchDocument = null; _lastSyntaxTree = GetSyntaxTree(); } internal ITextManagerAdapter TextManagerAdapter { get; set; } /// <summary> /// Internally, we store the DocumentId for the document that the FileCodeModel represents. If the underlying file /// is renamed, the DocumentId will become invalid because the Roslyn VS workspace treats file renames as a remove/add pair. /// To work around this, the FileCodeModel is notified when a file rename is about to occur. At that point, the /// <see cref="_documentId"/> field is null'd out and <see cref="_incomingFilePath"/> is set to the name of the new file. /// The next time that a FileCodeModel operation occurs that requires the DocumentId, it will be retrieved from the workspace /// using the <see cref="_incomingFilePath"/>. /// </summary> internal void OnRename(string newFilePath) { Debug.Assert(_editCount == 0, "FileCodeModel have an open edit and the underlying file is being renamed. This is a bug."); if (_documentId != null) { _previousDocument = Workspace.CurrentSolution.GetDocument(_documentId); } _incomingFilePath = newFilePath; _incomingProjectId = _documentId.ProjectId; _documentId = null; } internal override void Shutdown() { if (_invisibleEditor != null) { // we are shutting down, so do not worry about editCount. We will detach our format tracking from the text // buffer now; if anybody else had an invisible editor open to this file, we wouldn't want our format tracking // to trigger. We can safely do that on a background thread since it's just disconnecting a few event handlers. // We have to defer the shutdown of the invisible editor though as that requires talking to the UI thread. // We don't want to block up file removal on the UI thread since we want that path to stay asynchronous. CodeModelService.DetachFormatTrackingToBuffer(_invisibleEditor.TextBuffer); State.ProjectCodeModelFactory.ScheduleDeferredCleanupTask( cancellationToken => { // Ignore cancellationToken: we always need to call Dispose since it triggers the file save. _ = cancellationToken; _invisibleEditor.Dispose(); }); } base.Shutdown(); } private bool TryGetDocumentId(out DocumentId documentId) { if (_documentId != null) { documentId = _documentId; return true; } documentId = null; // We don't have DocumentId, so try to retrieve it from the workspace. if (_incomingProjectId == null || _incomingFilePath == null) { return false; } var project = this.State.Workspace.CurrentSolution.GetProject(_incomingProjectId); if (project == null) { return false; } documentId = project.Solution.GetDocumentIdsWithFilePath(_incomingFilePath).FirstOrDefault(d => d.ProjectId == project.Id); if (documentId == null) { return false; } _documentId = documentId; _incomingProjectId = null; _incomingFilePath = null; _previousDocument = null; return true; } internal DocumentId GetDocumentId() { if (_documentId != null) { return _documentId; } if (TryGetDocumentId(out var documentId)) { return documentId; } throw Exceptions.ThrowEUnexpected(); } internal void UpdateCodeElementNodeKey(AbstractKeyedCodeElement keyedElement, SyntaxNodeKey oldNodeKey, SyntaxNodeKey newNodeKey) { if (!_codeElementTable.TryGetValue(oldNodeKey, out var codeElement)) { throw new InvalidOperationException($"Could not find {oldNodeKey} in Code Model element table."); } _codeElementTable.Remove(oldNodeKey); var managedElement = ComAggregate.GetManagedObject<AbstractKeyedCodeElement>(codeElement); if (!object.Equals(managedElement, keyedElement)) { throw new InvalidOperationException($"Unexpected failure in Code Model while updating node keys {oldNodeKey} -> {newNodeKey}"); } // If we're updating this element with the same node key as an element that's already in the table, // just remove the old element. The old element will continue to function (through its node key), but // the new element will replace it in the cache. if (_codeElementTable.ContainsKey(newNodeKey)) { _codeElementTable.Remove(newNodeKey); } _codeElementTable.Add(newNodeKey, codeElement); } internal void OnCodeElementCreated(SyntaxNodeKey nodeKey, EnvDTE.CodeElement element) { // If we're updating this element with the same node key as an element that's already in the table, // just remove the old element. The old element will continue to function (through its node key), but // the new element will replace it in the cache. if (_codeElementTable.ContainsKey(nodeKey)) { _codeElementTable.Remove(nodeKey); } _codeElementTable.Add(nodeKey, element); } internal void OnCodeElementDeleted(SyntaxNodeKey nodeKey) => _codeElementTable.Remove(nodeKey); internal T GetOrCreateCodeElement<T>(SyntaxNode node) { var nodeKey = CodeModelService.TryGetNodeKey(node); if (!nodeKey.IsEmpty) { // Since the node already has a key, check to see if a code element already // exists for it. If so, return that element it it's still valid; otherwise, // remove it from the table. if (_codeElementTable.TryGetValue(nodeKey, out var codeElement)) { if (codeElement != null) { var element = ComAggregate.TryGetManagedObject<AbstractCodeElement>(codeElement); if (element.IsValidNode()) { if (codeElement is T tcodeElement) { return tcodeElement; } throw new InvalidOperationException($"Found a valid code element for {nodeKey}, but it is not of type, {typeof(T).ToString()}"); } } } // Go ahead and remove the nodeKey from the table. At this point, we'll be creating a new one. _codeElementTable.Remove(nodeKey); } return (T)CodeModelService.CreateInternalCodeElement(this.State, this, node); } private void InitializeEditor() { _editCount++; if (_editCount == 1) { Debug.Assert(_invisibleEditor == null); _invisibleEditor = Workspace.OpenInvisibleEditor(GetDocumentId()); CodeModelService.AttachFormatTrackingToBuffer(_invisibleEditor.TextBuffer); } } private void ReleaseEditor() { Debug.Assert(_editCount >= 1); _editCount--; if (_editCount == 0) { Debug.Assert(_invisibleEditor != null); CodeModelService.DetachFormatTrackingToBuffer(_invisibleEditor.TextBuffer); _invisibleEditor.Dispose(); _invisibleEditor = null; } } internal void EnsureEditor(Action action) { InitializeEditor(); try { action(); } finally { ReleaseEditor(); } } internal T EnsureEditor<T>(Func<T> action) { InitializeEditor(); try { return action(); } finally { ReleaseEditor(); } } internal void PerformEdit(Func<Document, Document> action) { EnsureEditor(() => { Debug.Assert(_invisibleEditor != null); var document = GetDocument(); var workspace = document.Project.Solution.Workspace; var result = action(document); var formatted = State.ThreadingContext.JoinableTaskFactory.Run(async () => { var formatted = await Formatter.FormatAsync(result, Formatter.Annotation).ConfigureAwait(true); formatted = await Formatter.FormatAsync(formatted, SyntaxAnnotation.ElasticAnnotation).ConfigureAwait(true); return formatted; }); ApplyChanges(workspace, formatted); }); } internal T PerformEdit<T>(Func<Document, Tuple<T, Document>> action) where T : SyntaxNode { return EnsureEditor(() => { Debug.Assert(_invisibleEditor != null); var document = GetDocument(); var workspace = document.Project.Solution.Workspace; var result = action(document); ApplyChanges(workspace, result.Item2); return result.Item1; }); } private void ApplyChanges(Workspace workspace, Document document) { if (IsBatchOpen) { _batchDocument = document; } else { workspace.TryApplyChanges(document.Project.Solution); } } internal Document GetDocument() { if (!TryGetDocument(out var document)) { throw Exceptions.ThrowEFail(); } return document; } internal bool TryGetDocument(out Document document) { if (IsBatchOpen && _batchDocument != null) { document = _batchDocument; return true; } if (!TryGetDocumentId(out _) && _previousDocument != null) { document = _previousDocument; } else { // HACK HACK HACK: Ensure we've processed all files being opened before we let designers work further. // In https://devdiv.visualstudio.com/DevDiv/_workitems/edit/728035, a file is opened in an invisible editor and contents are written // to it. The file isn't saved, but it's added to the workspace; we won't have yet hooked up to the open file since that work was deferred. // Since we're on the UI thread here, we can ensure those are all wired up since the analysis of this document may depend on that other file. // We choose to do this here rather than in the project system code when it's added because we don't want to pay the penalty of checking the RDT for // all files being opened on the UI thread if we really don't need it. This uses an 'as' cast, because in unit tests the workspace is a different // derived form of VisualStudioWorkspace, and there we aren't dealing with open files at all so it doesn't matter. (State.Workspace as VisualStudioWorkspaceImpl)?.ProcessQueuedWorkOnUIThread(); document = Workspace.CurrentSolution.GetDocument(GetDocumentId()); } return document != null; } internal SyntaxTree GetSyntaxTree() { return GetDocument().GetSyntaxTreeSynchronously(CancellationToken.None); } internal SyntaxNode GetSyntaxRoot() { return GetDocument().GetSyntaxRootSynchronously(CancellationToken.None); } internal SemanticModel GetSemanticModel() => State.ThreadingContext.JoinableTaskFactory.Run(() => { return GetDocument() .GetSemanticModelAsync(CancellationToken.None); }); internal Compilation GetCompilation() => State.ThreadingContext.JoinableTaskFactory.Run(() => { return GetDocument().Project .GetCompilationAsync(CancellationToken.None); }); internal ProjectId GetProjectId() => GetDocumentId().ProjectId; internal SyntaxNode LookupNode(SyntaxNodeKey nodeKey) => CodeModelService.LookupNode(nodeKey, GetSyntaxTree()); internal TSyntaxNode LookupNode<TSyntaxNode>(SyntaxNodeKey nodeKey) where TSyntaxNode : SyntaxNode { return CodeModelService.LookupNode(nodeKey, GetSyntaxTree()) as TSyntaxNode; } public EnvDTE.CodeAttribute AddAttribute(string name, string value, object position) { return EnsureEditor(() => { return AddAttribute(GetSyntaxRoot(), name, value, position, target: CodeModelService.AssemblyAttributeString); }); } public EnvDTE.CodeClass AddClass(string name, object position, object bases, object implementedInterfaces, EnvDTE.vsCMAccess access) { return EnsureEditor(() => { return AddClass(GetSyntaxRoot(), name, position, bases, implementedInterfaces, access); }); } public EnvDTE.CodeDelegate AddDelegate(string name, object type, object position, EnvDTE.vsCMAccess access) { return EnsureEditor(() => { return AddDelegate(GetSyntaxRoot(), name, type, position, access); }); } public EnvDTE.CodeEnum AddEnum(string name, object position, object bases, EnvDTE.vsCMAccess access) { return EnsureEditor(() => { return AddEnum(GetSyntaxRoot(), name, position, bases, access); }); } public EnvDTE.CodeFunction AddFunction(string name, EnvDTE.vsCMFunction kind, object type, object position, EnvDTE.vsCMAccess access) => throw Exceptions.ThrowEFail(); public EnvDTE80.CodeImport AddImport(string name, object position, string alias) { return EnsureEditor(() => { return AddImport(GetSyntaxRoot(), name, position, alias); }); } public EnvDTE.CodeInterface AddInterface(string name, object position, object bases, EnvDTE.vsCMAccess access) { return EnsureEditor(() => { return AddInterface(GetSyntaxRoot(), name, position, bases, access); }); } public EnvDTE.CodeNamespace AddNamespace(string name, object position) { return EnsureEditor(() => { return AddNamespace(GetSyntaxRoot(), name, position); }); } public EnvDTE.CodeStruct AddStruct(string name, object position, object bases, object implementedInterfaces, EnvDTE.vsCMAccess access) { return EnsureEditor(() => { return AddStruct(GetSyntaxRoot(), name, position, bases, implementedInterfaces, access); }); } public EnvDTE.CodeVariable AddVariable(string name, object type, object position, EnvDTE.vsCMAccess access) => throw Exceptions.ThrowEFail(); public EnvDTE.CodeElement CodeElementFromPoint(EnvDTE.TextPoint point, EnvDTE.vsCMElement scope) { // Can't use point.AbsoluteCharOffset because it's calculated by the native // implementation in GetAbsoluteOffset (in env\msenv\textmgr\autoutil.cpp) // to only count each newline as a single character. We need to ask for line and // column and calculate the right offset ourselves. See DevDiv2 530496 for details. var position = GetPositionFromTextPoint(point); var result = CodeElementFromPosition(position, scope); if (result == null) { throw Exceptions.ThrowEFail(); } return result; } private int GetPositionFromTextPoint(EnvDTE.TextPoint point) { var lineNumber = point.Line - 1; var column = point.LineCharOffset - 1; var line = GetDocument().GetTextSynchronously(CancellationToken.None).Lines[lineNumber]; var position = line.Start + column; return position; } internal EnvDTE.CodeElement CodeElementFromPosition(int position, EnvDTE.vsCMElement scope) { var root = GetSyntaxRoot(); var leftToken = root.FindTokenOnLeftOfPosition(position); var rightToken = root.FindTokenOnRightOfPosition(position); // We apply a set of heuristics to determine which member we pick to start searching. var token = leftToken; if (leftToken != rightToken) { if (leftToken.Span.End == position && rightToken.SpanStart == position) { // If both tokens are touching, we prefer identifiers and keywords to // separators. Note that the language doesn't allow both tokens to be a // keyword or identifier. if (SyntaxFactsService.IsReservedOrContextualKeyword(rightToken) || SyntaxFactsService.IsIdentifier(rightToken)) { token = rightToken; } } else if (leftToken.Span.End < position && rightToken.SpanStart <= position) { // If only the right token is touching, we have to use it. token = rightToken; } } // If we ended up using the left token but the position is after that token, // walk up to the first node who's last token is not the leftToken. By doing this, we // ensure that we don't find members when the position is actually between them. // In that case, we should find the enclosing type or namespace. var parent = token.Parent; if (token == leftToken && position > token.Span.End) { while (parent != null) { if (parent.GetLastToken() == token) { parent = parent.Parent; } else { break; } } } var node = parent?.AncestorsAndSelf().FirstOrDefault(n => CodeModelService.MatchesScope(n, scope)); if (node == null) { return null; } if (scope == EnvDTE.vsCMElement.vsCMElementAttribute || scope == EnvDTE.vsCMElement.vsCMElementImportStmt || scope == EnvDTE.vsCMElement.vsCMElementParameter || scope == EnvDTE.vsCMElement.vsCMElementOptionStmt || scope == EnvDTE.vsCMElement.vsCMElementInheritsStmt || scope == EnvDTE.vsCMElement.vsCMElementImplementsStmt || (scope == EnvDTE.vsCMElement.vsCMElementFunction && CodeModelService.IsAccessorNode(node))) { // Attributes, imports, parameters, Option, Inherits and Implements // don't have node keys of their own and won't be included in our // collection of elements. Delegate to the service to create these. return CodeModelService.CreateInternalCodeElement(State, this, node); } return GetOrCreateCodeElement<EnvDTE.CodeElement>(node); } public EnvDTE.CodeElements CodeElements { get { return NamespaceCollection.Create(this.State, this, this, SyntaxNodeKey.Empty); } } public EnvDTE.ProjectItem Parent { get { return _parentHandle.Object as EnvDTE.ProjectItem; } } public void Remove(object element) { var codeElement = ComAggregate.TryGetManagedObject<AbstractCodeElement>(element); if (codeElement == null) { codeElement = ComAggregate.TryGetManagedObject<AbstractCodeElement>(this.CodeElements.Item(element)); } if (codeElement == null) { throw new ArgumentException(ServicesVSResources.Element_is_not_valid, nameof(element)); } codeElement.Delete(); } int IVBFileCodeModelEvents.StartEdit() { try { InitializeEditor(); if (_editCount == 1) { _batchMode = true; _batchElements = new List<AbstractKeyedCodeElement>(); } return VSConstants.S_OK; } catch (Exception ex) { return Marshal.GetHRForException(ex); } } int IVBFileCodeModelEvents.EndEdit() { try { if (_editCount == 1) { List<ValueTuple<AbstractKeyedCodeElement, SyntaxPath>> elementAndPaths = null; if (_batchElements.Count > 0) { foreach (var element in _batchElements) { var node = element.LookupNode(); if (node != null) { elementAndPaths ??= new List<ValueTuple<AbstractKeyedCodeElement, SyntaxPath>>(); elementAndPaths.Add(ValueTuple.Create(element, new SyntaxPath(node))); } } } if (_batchDocument != null) { // perform expensive operations at once var newDocument = State.ThreadingContext.JoinableTaskFactory.Run(() => Simplifier.ReduceAsync(_batchDocument, Simplifier.Annotation, cancellationToken: CancellationToken.None)); _batchDocument.Project.Solution.Workspace.TryApplyChanges(newDocument.Project.Solution); // done using batch document _batchDocument = null; } // Ensure the file is prettylisted, even if we didn't make any edits CodeModelService.EnsureBufferFormatted(_invisibleEditor.TextBuffer); if (elementAndPaths != null) { foreach (var elementAndPath in elementAndPaths) { // make sure the element is there. if (_codeElementTable.TryGetValue(elementAndPath.Item1.NodeKey, out var existingElement)) { elementAndPath.Item1.ReacquireNodeKey(elementAndPath.Item2, CancellationToken.None); } // make sure existing element doesn't go away (weak reference) in the middle of // updating the node key GC.KeepAlive(existingElement); } } _batchMode = false; _batchElements = null; } return VSConstants.S_OK; } catch (Exception ex) { return Marshal.GetHRForException(ex); } finally { ReleaseEditor(); } } public void BeginBatch() { IVBFileCodeModelEvents temp = this; ErrorHandler.ThrowOnFailure(temp.StartEdit()); } public void EndBatch() { IVBFileCodeModelEvents temp = this; ErrorHandler.ThrowOnFailure(temp.EndEdit()); } public bool IsBatchOpen { get { return _batchMode && _editCount > 0; } } public EnvDTE.CodeElement ElementFromID(string id) => throw new NotImplementedException(); public EnvDTE80.vsCMParseStatus ParseStatus { get { var syntaxTree = GetSyntaxTree(); return syntaxTree.GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error) ? EnvDTE80.vsCMParseStatus.vsCMParseStatusError : EnvDTE80.vsCMParseStatus.vsCMParseStatusComplete; } } public void Synchronize() => FireEvents(); EnvDTE.CodeElements ICodeElementContainer<AbstractCodeElement>.GetCollection() => CodeElements; internal List<GlobalNodeKey> GetCurrentNodeKeys() { var currentNodeKeys = new List<GlobalNodeKey>(); foreach (var element in _codeElementTable.Values) { var keyedElement = ComAggregate.TryGetManagedObject<AbstractKeyedCodeElement>(element); if (keyedElement == null) { continue; } if (keyedElement.TryLookupNode(out var node)) { var nodeKey = keyedElement.NodeKey; currentNodeKeys.Add(new GlobalNodeKey(nodeKey, new SyntaxPath(node))); } } return currentNodeKeys; } internal void ResetElementKeys(List<GlobalNodeKey> globalNodeKeys) { foreach (var globalNodeKey in globalNodeKeys) { ResetElementKey(globalNodeKey); } } private void ResetElementKey(GlobalNodeKey globalNodeKey) { // Failure to find the element is not an error -- it just means the code // element didn't exist... if (_codeElementTable.TryGetValue(globalNodeKey.NodeKey, out var element)) { var keyedElement = ComAggregate.GetManagedObject<AbstractKeyedCodeElement>(element); if (keyedElement != null) { keyedElement.ReacquireNodeKey(globalNodeKey.Path, default); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel { /// <summary> /// Implementations of EnvDTE.FileCodeModel for both languages. /// </summary> public sealed partial class FileCodeModel : AbstractCodeModelObject, EnvDTE.FileCodeModel, EnvDTE80.FileCodeModel2, ICodeElementContainer<AbstractCodeElement>, IVBFileCodeModelEvents, ICSCodeModelRefactoring { internal static ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel> Create( CodeModelState state, object parent, DocumentId documentId, ITextManagerAdapter textManagerAdapter) { return new FileCodeModel(state, parent, documentId, textManagerAdapter).GetComHandle<EnvDTE80.FileCodeModel2, FileCodeModel>(); } private readonly ComHandle<object, object> _parentHandle; /// <summary> /// Don't use directly. Instead, call <see cref="GetDocumentId()"/>. /// </summary> private DocumentId _documentId; // Note: these are only valid when the underlying file is being renamed. Do not use. private ProjectId _incomingProjectId; private string _incomingFilePath; private Document _previousDocument; private readonly CleanableWeakComHandleTable<SyntaxNodeKey, EnvDTE.CodeElement> _codeElementTable; // These are used during batching. private bool _batchMode; private List<AbstractKeyedCodeElement> _batchElements; private Document _batchDocument; // track state to make sure we open editor only once private int _editCount; private IInvisibleEditor _invisibleEditor; private SyntaxTree _lastSyntaxTree; private FileCodeModel( CodeModelState state, object parent, DocumentId documentId, ITextManagerAdapter textManagerAdapter) : base(state) { Debug.Assert(documentId != null); Debug.Assert(textManagerAdapter != null); _parentHandle = new ComHandle<object, object>(parent); _documentId = documentId; TextManagerAdapter = textManagerAdapter; _codeElementTable = new CleanableWeakComHandleTable<SyntaxNodeKey, EnvDTE.CodeElement>(state.ThreadingContext); _batchMode = false; _batchDocument = null; _lastSyntaxTree = GetSyntaxTree(); } internal ITextManagerAdapter TextManagerAdapter { get; set; } /// <summary> /// Internally, we store the DocumentId for the document that the FileCodeModel represents. If the underlying file /// is renamed, the DocumentId will become invalid because the Roslyn VS workspace treats file renames as a remove/add pair. /// To work around this, the FileCodeModel is notified when a file rename is about to occur. At that point, the /// <see cref="_documentId"/> field is null'd out and <see cref="_incomingFilePath"/> is set to the name of the new file. /// The next time that a FileCodeModel operation occurs that requires the DocumentId, it will be retrieved from the workspace /// using the <see cref="_incomingFilePath"/>. /// </summary> internal void OnRename(string newFilePath) { Debug.Assert(_editCount == 0, "FileCodeModel have an open edit and the underlying file is being renamed. This is a bug."); if (_documentId != null) { _previousDocument = Workspace.CurrentSolution.GetDocument(_documentId); } _incomingFilePath = newFilePath; _incomingProjectId = _documentId.ProjectId; _documentId = null; } internal override void Shutdown() { if (_invisibleEditor != null) { // we are shutting down, so do not worry about editCount. We will detach our format tracking from the text // buffer now; if anybody else had an invisible editor open to this file, we wouldn't want our format tracking // to trigger. We can safely do that on a background thread since it's just disconnecting a few event handlers. // We have to defer the shutdown of the invisible editor though as that requires talking to the UI thread. // We don't want to block up file removal on the UI thread since we want that path to stay asynchronous. CodeModelService.DetachFormatTrackingToBuffer(_invisibleEditor.TextBuffer); State.ProjectCodeModelFactory.ScheduleDeferredCleanupTask( cancellationToken => { // Ignore cancellationToken: we always need to call Dispose since it triggers the file save. _ = cancellationToken; _invisibleEditor.Dispose(); }); } base.Shutdown(); } private bool TryGetDocumentId(out DocumentId documentId) { if (_documentId != null) { documentId = _documentId; return true; } documentId = null; // We don't have DocumentId, so try to retrieve it from the workspace. if (_incomingProjectId == null || _incomingFilePath == null) { return false; } var project = this.State.Workspace.CurrentSolution.GetProject(_incomingProjectId); if (project == null) { return false; } documentId = project.Solution.GetDocumentIdsWithFilePath(_incomingFilePath).FirstOrDefault(d => d.ProjectId == project.Id); if (documentId == null) { return false; } _documentId = documentId; _incomingProjectId = null; _incomingFilePath = null; _previousDocument = null; return true; } internal DocumentId GetDocumentId() { if (_documentId != null) { return _documentId; } if (TryGetDocumentId(out var documentId)) { return documentId; } throw Exceptions.ThrowEUnexpected(); } internal void UpdateCodeElementNodeKey(AbstractKeyedCodeElement keyedElement, SyntaxNodeKey oldNodeKey, SyntaxNodeKey newNodeKey) { if (!_codeElementTable.TryGetValue(oldNodeKey, out var codeElement)) { throw new InvalidOperationException($"Could not find {oldNodeKey} in Code Model element table."); } _codeElementTable.Remove(oldNodeKey); var managedElement = ComAggregate.GetManagedObject<AbstractKeyedCodeElement>(codeElement); if (!object.Equals(managedElement, keyedElement)) { throw new InvalidOperationException($"Unexpected failure in Code Model while updating node keys {oldNodeKey} -> {newNodeKey}"); } // If we're updating this element with the same node key as an element that's already in the table, // just remove the old element. The old element will continue to function (through its node key), but // the new element will replace it in the cache. if (_codeElementTable.ContainsKey(newNodeKey)) { _codeElementTable.Remove(newNodeKey); } _codeElementTable.Add(newNodeKey, codeElement); } internal void OnCodeElementCreated(SyntaxNodeKey nodeKey, EnvDTE.CodeElement element) { // If we're updating this element with the same node key as an element that's already in the table, // just remove the old element. The old element will continue to function (through its node key), but // the new element will replace it in the cache. if (_codeElementTable.ContainsKey(nodeKey)) { _codeElementTable.Remove(nodeKey); } _codeElementTable.Add(nodeKey, element); } internal void OnCodeElementDeleted(SyntaxNodeKey nodeKey) => _codeElementTable.Remove(nodeKey); internal T GetOrCreateCodeElement<T>(SyntaxNode node) { var nodeKey = CodeModelService.TryGetNodeKey(node); if (!nodeKey.IsEmpty) { // Since the node already has a key, check to see if a code element already // exists for it. If so, return that element it it's still valid; otherwise, // remove it from the table. if (_codeElementTable.TryGetValue(nodeKey, out var codeElement)) { if (codeElement != null) { var element = ComAggregate.TryGetManagedObject<AbstractCodeElement>(codeElement); if (element.IsValidNode()) { if (codeElement is T tcodeElement) { return tcodeElement; } throw new InvalidOperationException($"Found a valid code element for {nodeKey}, but it is not of type, {typeof(T).ToString()}"); } } } // Go ahead and remove the nodeKey from the table. At this point, we'll be creating a new one. _codeElementTable.Remove(nodeKey); } return (T)CodeModelService.CreateInternalCodeElement(this.State, this, node); } private void InitializeEditor() { _editCount++; if (_editCount == 1) { Debug.Assert(_invisibleEditor == null); _invisibleEditor = Workspace.OpenInvisibleEditor(GetDocumentId()); CodeModelService.AttachFormatTrackingToBuffer(_invisibleEditor.TextBuffer); } } private void ReleaseEditor() { Debug.Assert(_editCount >= 1); _editCount--; if (_editCount == 0) { Debug.Assert(_invisibleEditor != null); CodeModelService.DetachFormatTrackingToBuffer(_invisibleEditor.TextBuffer); _invisibleEditor.Dispose(); _invisibleEditor = null; } } internal void EnsureEditor(Action action) { InitializeEditor(); try { action(); } finally { ReleaseEditor(); } } internal T EnsureEditor<T>(Func<T> action) { InitializeEditor(); try { return action(); } finally { ReleaseEditor(); } } internal void PerformEdit(Func<Document, Document> action) { EnsureEditor(() => { Debug.Assert(_invisibleEditor != null); var document = GetDocument(); var workspace = document.Project.Solution.Workspace; var result = action(document); var formatted = State.ThreadingContext.JoinableTaskFactory.Run(async () => { var formatted = await Formatter.FormatAsync(result, Formatter.Annotation).ConfigureAwait(true); formatted = await Formatter.FormatAsync(formatted, SyntaxAnnotation.ElasticAnnotation).ConfigureAwait(true); return formatted; }); ApplyChanges(workspace, formatted); }); } internal T PerformEdit<T>(Func<Document, Tuple<T, Document>> action) where T : SyntaxNode { return EnsureEditor(() => { Debug.Assert(_invisibleEditor != null); var document = GetDocument(); var workspace = document.Project.Solution.Workspace; var result = action(document); ApplyChanges(workspace, result.Item2); return result.Item1; }); } private void ApplyChanges(Workspace workspace, Document document) { if (IsBatchOpen) { _batchDocument = document; } else { workspace.TryApplyChanges(document.Project.Solution); } } internal Document GetDocument() { if (!TryGetDocument(out var document)) { throw Exceptions.ThrowEFail(); } return document; } internal bool TryGetDocument(out Document document) { if (IsBatchOpen && _batchDocument != null) { document = _batchDocument; return true; } if (!TryGetDocumentId(out _) && _previousDocument != null) { document = _previousDocument; } else { // HACK HACK HACK: Ensure we've processed all files being opened before we let designers work further. // In https://devdiv.visualstudio.com/DevDiv/_workitems/edit/728035, a file is opened in an invisible editor and contents are written // to it. The file isn't saved, but it's added to the workspace; we won't have yet hooked up to the open file since that work was deferred. // Since we're on the UI thread here, we can ensure those are all wired up since the analysis of this document may depend on that other file. // We choose to do this here rather than in the project system code when it's added because we don't want to pay the penalty of checking the RDT for // all files being opened on the UI thread if we really don't need it. This uses an 'as' cast, because in unit tests the workspace is a different // derived form of VisualStudioWorkspace, and there we aren't dealing with open files at all so it doesn't matter. (State.Workspace as VisualStudioWorkspaceImpl)?.ProcessQueuedWorkOnUIThread(); document = Workspace.CurrentSolution.GetDocument(GetDocumentId()); } return document != null; } internal SyntaxTree GetSyntaxTree() { return GetDocument().GetSyntaxTreeSynchronously(CancellationToken.None); } internal SyntaxNode GetSyntaxRoot() { return GetDocument().GetSyntaxRootSynchronously(CancellationToken.None); } internal SemanticModel GetSemanticModel() => State.ThreadingContext.JoinableTaskFactory.Run(() => { return GetDocument() .GetSemanticModelAsync(CancellationToken.None); }); internal Compilation GetCompilation() => State.ThreadingContext.JoinableTaskFactory.Run(() => { return GetDocument().Project .GetCompilationAsync(CancellationToken.None); }); internal ProjectId GetProjectId() => GetDocumentId().ProjectId; internal SyntaxNode LookupNode(SyntaxNodeKey nodeKey) => CodeModelService.LookupNode(nodeKey, GetSyntaxTree()); internal TSyntaxNode LookupNode<TSyntaxNode>(SyntaxNodeKey nodeKey) where TSyntaxNode : SyntaxNode { return CodeModelService.LookupNode(nodeKey, GetSyntaxTree()) as TSyntaxNode; } public EnvDTE.CodeAttribute AddAttribute(string name, string value, object position) { return EnsureEditor(() => { return AddAttribute(GetSyntaxRoot(), name, value, position, target: CodeModelService.AssemblyAttributeString); }); } public EnvDTE.CodeClass AddClass(string name, object position, object bases, object implementedInterfaces, EnvDTE.vsCMAccess access) { return EnsureEditor(() => { return AddClass(GetSyntaxRoot(), name, position, bases, implementedInterfaces, access); }); } public EnvDTE.CodeDelegate AddDelegate(string name, object type, object position, EnvDTE.vsCMAccess access) { return EnsureEditor(() => { return AddDelegate(GetSyntaxRoot(), name, type, position, access); }); } public EnvDTE.CodeEnum AddEnum(string name, object position, object bases, EnvDTE.vsCMAccess access) { return EnsureEditor(() => { return AddEnum(GetSyntaxRoot(), name, position, bases, access); }); } public EnvDTE.CodeFunction AddFunction(string name, EnvDTE.vsCMFunction kind, object type, object position, EnvDTE.vsCMAccess access) => throw Exceptions.ThrowEFail(); public EnvDTE80.CodeImport AddImport(string name, object position, string alias) { return EnsureEditor(() => { return AddImport(GetSyntaxRoot(), name, position, alias); }); } public EnvDTE.CodeInterface AddInterface(string name, object position, object bases, EnvDTE.vsCMAccess access) { return EnsureEditor(() => { return AddInterface(GetSyntaxRoot(), name, position, bases, access); }); } public EnvDTE.CodeNamespace AddNamespace(string name, object position) { return EnsureEditor(() => { return AddNamespace(GetSyntaxRoot(), name, position); }); } public EnvDTE.CodeStruct AddStruct(string name, object position, object bases, object implementedInterfaces, EnvDTE.vsCMAccess access) { return EnsureEditor(() => { return AddStruct(GetSyntaxRoot(), name, position, bases, implementedInterfaces, access); }); } public EnvDTE.CodeVariable AddVariable(string name, object type, object position, EnvDTE.vsCMAccess access) => throw Exceptions.ThrowEFail(); public EnvDTE.CodeElement CodeElementFromPoint(EnvDTE.TextPoint point, EnvDTE.vsCMElement scope) { // Can't use point.AbsoluteCharOffset because it's calculated by the native // implementation in GetAbsoluteOffset (in env\msenv\textmgr\autoutil.cpp) // to only count each newline as a single character. We need to ask for line and // column and calculate the right offset ourselves. See DevDiv2 530496 for details. var position = GetPositionFromTextPoint(point); var result = CodeElementFromPosition(position, scope); if (result == null) { throw Exceptions.ThrowEFail(); } return result; } private int GetPositionFromTextPoint(EnvDTE.TextPoint point) { var lineNumber = point.Line - 1; var column = point.LineCharOffset - 1; var line = GetDocument().GetTextSynchronously(CancellationToken.None).Lines[lineNumber]; var position = line.Start + column; return position; } internal EnvDTE.CodeElement CodeElementFromPosition(int position, EnvDTE.vsCMElement scope) { var root = GetSyntaxRoot(); var leftToken = root.FindTokenOnLeftOfPosition(position); var rightToken = root.FindTokenOnRightOfPosition(position); // We apply a set of heuristics to determine which member we pick to start searching. var token = leftToken; if (leftToken != rightToken) { if (leftToken.Span.End == position && rightToken.SpanStart == position) { // If both tokens are touching, we prefer identifiers and keywords to // separators. Note that the language doesn't allow both tokens to be a // keyword or identifier. if (SyntaxFactsService.IsReservedOrContextualKeyword(rightToken) || SyntaxFactsService.IsIdentifier(rightToken)) { token = rightToken; } } else if (leftToken.Span.End < position && rightToken.SpanStart <= position) { // If only the right token is touching, we have to use it. token = rightToken; } } // If we ended up using the left token but the position is after that token, // walk up to the first node who's last token is not the leftToken. By doing this, we // ensure that we don't find members when the position is actually between them. // In that case, we should find the enclosing type or namespace. var parent = token.Parent; if (token == leftToken && position > token.Span.End) { while (parent != null) { if (parent.GetLastToken() == token) { parent = parent.Parent; } else { break; } } } var node = parent?.AncestorsAndSelf().FirstOrDefault(n => CodeModelService.MatchesScope(n, scope)); if (node == null) { return null; } if (scope == EnvDTE.vsCMElement.vsCMElementAttribute || scope == EnvDTE.vsCMElement.vsCMElementImportStmt || scope == EnvDTE.vsCMElement.vsCMElementParameter || scope == EnvDTE.vsCMElement.vsCMElementOptionStmt || scope == EnvDTE.vsCMElement.vsCMElementInheritsStmt || scope == EnvDTE.vsCMElement.vsCMElementImplementsStmt || (scope == EnvDTE.vsCMElement.vsCMElementFunction && CodeModelService.IsAccessorNode(node))) { // Attributes, imports, parameters, Option, Inherits and Implements // don't have node keys of their own and won't be included in our // collection of elements. Delegate to the service to create these. return CodeModelService.CreateInternalCodeElement(State, this, node); } return GetOrCreateCodeElement<EnvDTE.CodeElement>(node); } public EnvDTE.CodeElements CodeElements { get { return NamespaceCollection.Create(this.State, this, this, SyntaxNodeKey.Empty); } } public EnvDTE.ProjectItem Parent { get { return _parentHandle.Object as EnvDTE.ProjectItem; } } public void Remove(object element) { var codeElement = ComAggregate.TryGetManagedObject<AbstractCodeElement>(element); if (codeElement == null) { codeElement = ComAggregate.TryGetManagedObject<AbstractCodeElement>(this.CodeElements.Item(element)); } if (codeElement == null) { throw new ArgumentException(ServicesVSResources.Element_is_not_valid, nameof(element)); } codeElement.Delete(); } int IVBFileCodeModelEvents.StartEdit() { try { InitializeEditor(); if (_editCount == 1) { _batchMode = true; _batchElements = new List<AbstractKeyedCodeElement>(); } return VSConstants.S_OK; } catch (Exception ex) { return Marshal.GetHRForException(ex); } } int IVBFileCodeModelEvents.EndEdit() { try { if (_editCount == 1) { List<ValueTuple<AbstractKeyedCodeElement, SyntaxPath>> elementAndPaths = null; if (_batchElements.Count > 0) { foreach (var element in _batchElements) { var node = element.LookupNode(); if (node != null) { elementAndPaths ??= new List<ValueTuple<AbstractKeyedCodeElement, SyntaxPath>>(); elementAndPaths.Add(ValueTuple.Create(element, new SyntaxPath(node))); } } } if (_batchDocument != null) { // perform expensive operations at once var newDocument = State.ThreadingContext.JoinableTaskFactory.Run(() => Simplifier.ReduceAsync(_batchDocument, Simplifier.Annotation, cancellationToken: CancellationToken.None)); _batchDocument.Project.Solution.Workspace.TryApplyChanges(newDocument.Project.Solution); // done using batch document _batchDocument = null; } // Ensure the file is prettylisted, even if we didn't make any edits CodeModelService.EnsureBufferFormatted(_invisibleEditor.TextBuffer); if (elementAndPaths != null) { foreach (var elementAndPath in elementAndPaths) { // make sure the element is there. if (_codeElementTable.TryGetValue(elementAndPath.Item1.NodeKey, out var existingElement)) { elementAndPath.Item1.ReacquireNodeKey(elementAndPath.Item2, CancellationToken.None); } // make sure existing element doesn't go away (weak reference) in the middle of // updating the node key GC.KeepAlive(existingElement); } } _batchMode = false; _batchElements = null; } return VSConstants.S_OK; } catch (Exception ex) { return Marshal.GetHRForException(ex); } finally { ReleaseEditor(); } } public void BeginBatch() { IVBFileCodeModelEvents temp = this; ErrorHandler.ThrowOnFailure(temp.StartEdit()); } public void EndBatch() { IVBFileCodeModelEvents temp = this; ErrorHandler.ThrowOnFailure(temp.EndEdit()); } public bool IsBatchOpen { get { return _batchMode && _editCount > 0; } } public EnvDTE.CodeElement ElementFromID(string id) => throw new NotImplementedException(); public EnvDTE80.vsCMParseStatus ParseStatus { get { var syntaxTree = GetSyntaxTree(); return syntaxTree.GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error) ? EnvDTE80.vsCMParseStatus.vsCMParseStatusError : EnvDTE80.vsCMParseStatus.vsCMParseStatusComplete; } } public void Synchronize() => FireEvents(); EnvDTE.CodeElements ICodeElementContainer<AbstractCodeElement>.GetCollection() => CodeElements; internal List<GlobalNodeKey> GetCurrentNodeKeys() { var currentNodeKeys = new List<GlobalNodeKey>(); foreach (var element in _codeElementTable.Values) { var keyedElement = ComAggregate.TryGetManagedObject<AbstractKeyedCodeElement>(element); if (keyedElement == null) { continue; } if (keyedElement.TryLookupNode(out var node)) { var nodeKey = keyedElement.NodeKey; currentNodeKeys.Add(new GlobalNodeKey(nodeKey, new SyntaxPath(node))); } } return currentNodeKeys; } internal void ResetElementKeys(List<GlobalNodeKey> globalNodeKeys) { foreach (var globalNodeKey in globalNodeKeys) { ResetElementKey(globalNodeKey); } } private void ResetElementKey(GlobalNodeKey globalNodeKey) { // Failure to find the element is not an error -- it just means the code // element didn't exist... if (_codeElementTable.TryGetValue(globalNodeKey.NodeKey, out var element)) { var keyedElement = ComAggregate.GetManagedObject<AbstractKeyedCodeElement>(element); if (keyedElement != null) { keyedElement.ReacquireNodeKey(globalNodeKey.Path, default); } } } } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/Compilers/CSharp/Portable/Utilities/ValueSetFactory.BoolValueSetFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { using static BinaryOperatorKind; internal static partial class ValueSetFactory { /// <summary> /// A value set factory for boolean values. /// </summary> private sealed class BoolValueSetFactory : IValueSetFactory<bool> { public static readonly BoolValueSetFactory Instance = new BoolValueSetFactory(); private BoolValueSetFactory() { } IValueSet IValueSetFactory.AllValues => BoolValueSet.AllValues; IValueSet IValueSetFactory.NoValues => BoolValueSet.None; public IValueSet<bool> Related(BinaryOperatorKind relation, bool value) { switch (relation, value) { case (Equal, true): return BoolValueSet.OnlyTrue; case (Equal, false): return BoolValueSet.OnlyFalse; default: // for error recovery return BoolValueSet.AllValues; } } IValueSet IValueSetFactory.Random(int expectedSize, Random random) => random.Next(4) switch { 0 => BoolValueSet.None, 1 => BoolValueSet.OnlyFalse, 2 => BoolValueSet.OnlyTrue, 3 => BoolValueSet.AllValues, _ => throw ExceptionUtilities.UnexpectedValue("random"), }; ConstantValue IValueSetFactory.RandomValue(Random random) => ConstantValue.Create(random.NextDouble() < 0.5); IValueSet IValueSetFactory.Related(BinaryOperatorKind relation, ConstantValue value) { return value.IsBad ? BoolValueSet.AllValues : Related(relation, value.BooleanValue); } bool IValueSetFactory.Related(BinaryOperatorKind relation, ConstantValue left, ConstantValue right) { Debug.Assert(relation == BinaryOperatorKind.Equal); return left.IsBad || right.IsBad || left.BooleanValue == right.BooleanValue; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { using static BinaryOperatorKind; internal static partial class ValueSetFactory { /// <summary> /// A value set factory for boolean values. /// </summary> private sealed class BoolValueSetFactory : IValueSetFactory<bool> { public static readonly BoolValueSetFactory Instance = new BoolValueSetFactory(); private BoolValueSetFactory() { } IValueSet IValueSetFactory.AllValues => BoolValueSet.AllValues; IValueSet IValueSetFactory.NoValues => BoolValueSet.None; public IValueSet<bool> Related(BinaryOperatorKind relation, bool value) { switch (relation, value) { case (Equal, true): return BoolValueSet.OnlyTrue; case (Equal, false): return BoolValueSet.OnlyFalse; default: // for error recovery return BoolValueSet.AllValues; } } IValueSet IValueSetFactory.Random(int expectedSize, Random random) => random.Next(4) switch { 0 => BoolValueSet.None, 1 => BoolValueSet.OnlyFalse, 2 => BoolValueSet.OnlyTrue, 3 => BoolValueSet.AllValues, _ => throw ExceptionUtilities.UnexpectedValue("random"), }; ConstantValue IValueSetFactory.RandomValue(Random random) => ConstantValue.Create(random.NextDouble() < 0.5); IValueSet IValueSetFactory.Related(BinaryOperatorKind relation, ConstantValue value) { return value.IsBad ? BoolValueSet.AllValues : Related(relation, value.BooleanValue); } bool IValueSetFactory.Related(BinaryOperatorKind relation, ConstantValue left, ConstantValue right) { Debug.Assert(relation == BinaryOperatorKind.Equal); return left.IsBad || right.IsBad || left.BooleanValue == right.BooleanValue; } } } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/Analyzers/VisualBasic/CodeFixes/xlf/VisualBasicCodeFixesResources.zh-Hant.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="zh-Hant" original="../VisualBasicCodeFixesResources.resx"> <body> <trans-unit id="Add_Me"> <source>Add 'Me.'</source> <target state="translated">新增 'Me.'</target> <note /> </trans-unit> <trans-unit id="Convert_GetType_to_NameOf"> <source>Convert 'GetType' to 'NameOf'</source> <target state="translated">將 'GetType' 轉換為 'NameOf'</target> <note /> </trans-unit> <trans-unit id="Remove_Unnecessary_Imports"> <source>Remove Unnecessary Imports</source> <target state="translated">移除不必要的匯入</target> <note /> </trans-unit> <trans-unit id="Simplify_object_creation"> <source>Simplify object creation</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="zh-Hant" original="../VisualBasicCodeFixesResources.resx"> <body> <trans-unit id="Add_Me"> <source>Add 'Me.'</source> <target state="translated">新增 'Me.'</target> <note /> </trans-unit> <trans-unit id="Convert_GetType_to_NameOf"> <source>Convert 'GetType' to 'NameOf'</source> <target state="translated">將 'GetType' 轉換為 'NameOf'</target> <note /> </trans-unit> <trans-unit id="Remove_Unnecessary_Imports"> <source>Remove Unnecessary Imports</source> <target state="translated">移除不必要的匯入</target> <note /> </trans-unit> <trans-unit id="Simplify_object_creation"> <source>Simplify object creation</source> <target state="translated">簡化物件建立</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/Workspaces/Remote/Core/BrokeredServiceConnection.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Pipelines; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Extensions; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.ServiceHub.Framework; using Microsoft.VisualStudio.Threading; using Roslyn.Utilities; using StreamJsonRpc; using StreamJsonRpc.Protocol; namespace Microsoft.CodeAnalysis.Remote { internal sealed class BrokeredServiceConnection<TService> : RemoteServiceConnection<TService> where TService : class { private readonly struct Rental : IDisposable { #pragma warning disable ISB002 // Avoid storing rentals in fields private readonly ServiceBrokerClient.Rental<TService> _proxyRental; #pragma warning restore public readonly TService Service; public Rental(ServiceBrokerClient.Rental<TService> proxyRental, TService service) { _proxyRental = proxyRental; Service = service; } public void Dispose() => _proxyRental.Dispose(); } private readonly IErrorReportingService? _errorReportingService; private readonly IRemoteHostClientShutdownCancellationService? _shutdownCancellationService; private readonly SolutionAssetStorage _solutionAssetStorage; private readonly ServiceDescriptor _serviceDescriptor; private readonly ServiceBrokerClient _serviceBrokerClient; private readonly RemoteServiceCallbackDispatcher.Handle _callbackHandle; private readonly IRemoteServiceCallbackDispatcher? _callbackDispatcher; public BrokeredServiceConnection( ServiceDescriptor serviceDescriptor, object? callbackTarget, IRemoteServiceCallbackDispatcher? callbackDispatcher, ServiceBrokerClient serviceBrokerClient, SolutionAssetStorage solutionAssetStorage, IErrorReportingService? errorReportingService, IRemoteHostClientShutdownCancellationService? shutdownCancellationService) { Contract.ThrowIfFalse((callbackDispatcher == null) == (serviceDescriptor.ClientInterface == null)); _serviceDescriptor = serviceDescriptor; _serviceBrokerClient = serviceBrokerClient; _solutionAssetStorage = solutionAssetStorage; _errorReportingService = errorReportingService; _shutdownCancellationService = shutdownCancellationService; _callbackDispatcher = callbackDispatcher; _callbackHandle = callbackDispatcher?.CreateHandle(callbackTarget) ?? default; } public override void Dispose() { _callbackHandle.Dispose(); } private async ValueTask<Rental> RentServiceAsync(CancellationToken cancellationToken) { // Make sure we are on the thread pool to avoid UI thread dependencies if external code uses ConfigureAwait(true) await TaskScheduler.Default; var options = new ServiceActivationOptions { ClientRpcTarget = _callbackDispatcher }; var proxyRental = await _serviceBrokerClient.GetProxyAsync<TService>(_serviceDescriptor, options, cancellationToken).ConfigureAwait(false); var service = proxyRental.Proxy; Contract.ThrowIfNull(service); return new Rental(proxyRental, service); } // no solution, no callback public override async ValueTask<bool> TryInvokeAsync(Func<TService, CancellationToken, ValueTask> invocation, CancellationToken cancellationToken) { try { using var rental = await RentServiceAsync(cancellationToken).ConfigureAwait(false); await invocation(rental.Service, cancellationToken).ConfigureAwait(false); return true; } catch (Exception exception) when (ReportUnexpectedException(exception, cancellationToken)) { OnUnexpectedException(exception, cancellationToken); return false; } } public override async ValueTask<Optional<TResult>> TryInvokeAsync<TResult>(Func<TService, CancellationToken, ValueTask<TResult>> invocation, CancellationToken cancellationToken) { try { using var rental = await RentServiceAsync(cancellationToken).ConfigureAwait(false); return await invocation(rental.Service, cancellationToken).ConfigureAwait(false); } catch (Exception exception) when (ReportUnexpectedException(exception, cancellationToken)) { OnUnexpectedException(exception, cancellationToken); return default; } } // no solution, callback public override async ValueTask<bool> TryInvokeAsync(Func<TService, RemoteServiceCallbackId, CancellationToken, ValueTask> invocation, CancellationToken cancellationToken) { Contract.ThrowIfFalse(_callbackDispatcher is not null); try { using var rental = await RentServiceAsync(cancellationToken).ConfigureAwait(false); await invocation(rental.Service, _callbackHandle.Id, cancellationToken).ConfigureAwait(false); return true; } catch (Exception exception) when (ReportUnexpectedException(exception, cancellationToken)) { OnUnexpectedException(exception, cancellationToken); return false; } } public override async ValueTask<Optional<TResult>> TryInvokeAsync<TResult>(Func<TService, RemoteServiceCallbackId, CancellationToken, ValueTask<TResult>> invocation, CancellationToken cancellationToken) { Contract.ThrowIfFalse(_callbackDispatcher is not null); try { using var rental = await RentServiceAsync(cancellationToken).ConfigureAwait(false); return await invocation(rental.Service, _callbackHandle.Id, cancellationToken).ConfigureAwait(false); } catch (Exception exception) when (ReportUnexpectedException(exception, cancellationToken)) { OnUnexpectedException(exception, cancellationToken); return default; } } // solution, no callback public override async ValueTask<bool> TryInvokeAsync(Solution solution, Func<TService, PinnedSolutionInfo, CancellationToken, ValueTask> invocation, CancellationToken cancellationToken) { try { using var scope = await _solutionAssetStorage.StoreAssetsAsync(solution, cancellationToken).ConfigureAwait(false); using var rental = await RentServiceAsync(cancellationToken).ConfigureAwait(false); await invocation(rental.Service, scope.SolutionInfo, cancellationToken).ConfigureAwait(false); return true; } catch (Exception exception) when (ReportUnexpectedException(exception, cancellationToken)) { OnUnexpectedException(exception, cancellationToken); return false; } } public override async ValueTask<Optional<TResult>> TryInvokeAsync<TResult>(Solution solution, Func<TService, PinnedSolutionInfo, CancellationToken, ValueTask<TResult>> invocation, CancellationToken cancellationToken) { try { using var scope = await _solutionAssetStorage.StoreAssetsAsync(solution, cancellationToken).ConfigureAwait(false); using var rental = await RentServiceAsync(cancellationToken).ConfigureAwait(false); return await invocation(rental.Service, scope.SolutionInfo, cancellationToken).ConfigureAwait(false); } catch (Exception exception) when (ReportUnexpectedException(exception, cancellationToken)) { OnUnexpectedException(exception, cancellationToken); return default; } } // project, no callback public override async ValueTask<bool> TryInvokeAsync(Project project, Func<TService, PinnedSolutionInfo, CancellationToken, ValueTask> invocation, CancellationToken cancellationToken) { try { using var scope = await _solutionAssetStorage.StoreAssetsAsync(project, cancellationToken).ConfigureAwait(false); using var rental = await RentServiceAsync(cancellationToken).ConfigureAwait(false); await invocation(rental.Service, scope.SolutionInfo, cancellationToken).ConfigureAwait(false); return true; } catch (Exception exception) when (ReportUnexpectedException(exception, cancellationToken)) { OnUnexpectedException(exception, cancellationToken); return false; } } public override async ValueTask<Optional<TResult>> TryInvokeAsync<TResult>(Project project, Func<TService, PinnedSolutionInfo, CancellationToken, ValueTask<TResult>> invocation, CancellationToken cancellationToken) { try { using var scope = await _solutionAssetStorage.StoreAssetsAsync(project, cancellationToken).ConfigureAwait(false); using var rental = await RentServiceAsync(cancellationToken).ConfigureAwait(false); return await invocation(rental.Service, scope.SolutionInfo, cancellationToken).ConfigureAwait(false); } catch (Exception exception) when (ReportUnexpectedException(exception, cancellationToken)) { OnUnexpectedException(exception, cancellationToken); return default; } } // solution, callback public override async ValueTask<bool> TryInvokeAsync(Solution solution, Func<TService, PinnedSolutionInfo, RemoteServiceCallbackId, CancellationToken, ValueTask> invocation, CancellationToken cancellationToken) { Contract.ThrowIfFalse(_callbackDispatcher is not null); try { using var scope = await _solutionAssetStorage.StoreAssetsAsync(solution, cancellationToken).ConfigureAwait(false); using var rental = await RentServiceAsync(cancellationToken).ConfigureAwait(false); await invocation(rental.Service, scope.SolutionInfo, _callbackHandle.Id, cancellationToken).ConfigureAwait(false); return true; } catch (Exception exception) when (ReportUnexpectedException(exception, cancellationToken)) { OnUnexpectedException(exception, cancellationToken); return false; } } public override async ValueTask<Optional<TResult>> TryInvokeAsync<TResult>(Solution solution, Func<TService, PinnedSolutionInfo, RemoteServiceCallbackId, CancellationToken, ValueTask<TResult>> invocation, CancellationToken cancellationToken) { Contract.ThrowIfFalse(_callbackDispatcher is not null); try { using var scope = await _solutionAssetStorage.StoreAssetsAsync(solution, cancellationToken).ConfigureAwait(false); using var rental = await RentServiceAsync(cancellationToken).ConfigureAwait(false); return await invocation(rental.Service, scope.SolutionInfo, _callbackHandle.Id, cancellationToken).ConfigureAwait(false); } catch (Exception exception) when (ReportUnexpectedException(exception, cancellationToken)) { OnUnexpectedException(exception, cancellationToken); return default; } } // project, callback public override async ValueTask<bool> TryInvokeAsync(Project project, Func<TService, PinnedSolutionInfo, RemoteServiceCallbackId, CancellationToken, ValueTask> invocation, CancellationToken cancellationToken) { Contract.ThrowIfFalse(_callbackDispatcher is not null); try { using var scope = await _solutionAssetStorage.StoreAssetsAsync(project, cancellationToken).ConfigureAwait(false); using var rental = await RentServiceAsync(cancellationToken).ConfigureAwait(false); await invocation(rental.Service, scope.SolutionInfo, _callbackHandle.Id, cancellationToken).ConfigureAwait(false); return true; } catch (Exception exception) when (ReportUnexpectedException(exception, cancellationToken)) { OnUnexpectedException(exception, cancellationToken); return false; } } public override async ValueTask<Optional<TResult>> TryInvokeAsync<TResult>(Project project, Func<TService, PinnedSolutionInfo, RemoteServiceCallbackId, CancellationToken, ValueTask<TResult>> invocation, CancellationToken cancellationToken) { Contract.ThrowIfFalse(_callbackDispatcher is not null); try { using var scope = await _solutionAssetStorage.StoreAssetsAsync(project, cancellationToken).ConfigureAwait(false); using var rental = await RentServiceAsync(cancellationToken).ConfigureAwait(false); return await invocation(rental.Service, scope.SolutionInfo, _callbackHandle.Id, cancellationToken).ConfigureAwait(false); } catch (Exception exception) when (ReportUnexpectedException(exception, cancellationToken)) { OnUnexpectedException(exception, cancellationToken); return default; } } // streaming public override async ValueTask<Optional<TResult>> TryInvokeAsync<TResult>( Func<TService, PipeWriter, CancellationToken, ValueTask> invocation, Func<PipeReader, CancellationToken, ValueTask<TResult>> reader, CancellationToken cancellationToken) { try { using var rental = await RentServiceAsync(cancellationToken).ConfigureAwait(false); return await InvokeStreamingServiceAsync(rental.Service, invocation, reader, cancellationToken).ConfigureAwait(false); } catch (Exception exception) when (ReportUnexpectedException(exception, cancellationToken)) { OnUnexpectedException(exception, cancellationToken); return default; } } public override async ValueTask<Optional<TResult>> TryInvokeAsync<TResult>( Solution solution, Func<TService, PinnedSolutionInfo, PipeWriter, CancellationToken, ValueTask> invocation, Func<PipeReader, CancellationToken, ValueTask<TResult>> reader, CancellationToken cancellationToken) { try { using var scope = await _solutionAssetStorage.StoreAssetsAsync(solution, cancellationToken).ConfigureAwait(false); using var rental = await RentServiceAsync(cancellationToken).ConfigureAwait(false); return await InvokeStreamingServiceAsync( rental.Service, (service, pipeWriter, cancellationToken) => invocation(service, scope.SolutionInfo, pipeWriter, cancellationToken), reader, cancellationToken).ConfigureAwait(false); } catch (Exception exception) when (ReportUnexpectedException(exception, cancellationToken)) { OnUnexpectedException(exception, cancellationToken); return default; } } public override async ValueTask<Optional<TResult>> TryInvokeAsync<TResult>( Project project, Func<TService, PinnedSolutionInfo, PipeWriter, CancellationToken, ValueTask> invocation, Func<PipeReader, CancellationToken, ValueTask<TResult>> reader, CancellationToken cancellationToken) { try { using var scope = await _solutionAssetStorage.StoreAssetsAsync(project, cancellationToken).ConfigureAwait(false); using var rental = await RentServiceAsync(cancellationToken).ConfigureAwait(false); return await InvokeStreamingServiceAsync( rental.Service, (service, pipeWriter, cancellationToken) => invocation(service, scope.SolutionInfo, pipeWriter, cancellationToken), reader, cancellationToken).ConfigureAwait(false); } catch (Exception exception) when (ReportUnexpectedException(exception, cancellationToken)) { OnUnexpectedException(exception, cancellationToken); return default; } } /// <param name="service">The service instance.</param> /// <param name="invocation">A callback to asynchronously write data. The callback is required to complete the /// <see cref="PipeWriter"/> except in cases where the callback throws an exception.</param> /// <param name="reader">A callback to asynchronously read data. The callback is allowed, but not required, to /// complete the <see cref="PipeReader"/>.</param> /// <param name="cancellationToken">A cancellation token the operation will observe.</param> internal static async ValueTask<TResult> InvokeStreamingServiceAsync<TResult>( TService service, Func<TService, PipeWriter, CancellationToken, ValueTask> invocation, Func<PipeReader, CancellationToken, ValueTask<TResult>> reader, CancellationToken cancellationToken) { // We can cancel at entry, but once the pipe operations are scheduled we rely on both operations running to // avoid deadlocks (the exception handler in 'writerTask' ensures progress is made in 'readerTask'). cancellationToken.ThrowIfCancellationRequested(); var mustNotCancelToken = CancellationToken.None; // After this point, the full cancellation sequence is as follows: // 1. 'cancellationToken' indicates cancellation is requested // 2. 'invocation' and 'readerTask' have cancellation requested // 3. 'invocation' stops writing to 'pipe.Writer' // 4. 'pipe.Writer' is completed // 5. 'readerTask' continues reading until EndOfStreamException (workaround for https://github.com/AArnott/Nerdbank.Streams/issues/361) // 6. 'pipe.Reader' is completed // 7. OperationCanceledException is thrown back to the caller var pipe = new Pipe(); // Create new tasks that both start executing, rather than invoking the delegates directly // to make sure both invocation and reader start executing and transfering data. var writerTask = Task.Run(async () => { try { await invocation(service, pipe.Writer, cancellationToken).ConfigureAwait(false); } catch (Exception e) { // Ensure that the writer is complete if an exception is thrown // before the writer is passed to the RPC proxy. Once it's passed to the proxy // the proxy should complete it as soon as the remote side completes it. await pipe.Writer.CompleteAsync(e).ConfigureAwait(false); throw; } }, mustNotCancelToken); var readerTask = Task.Run( async () => { Exception? exception = null; try { return await reader(pipe.Reader, cancellationToken).ConfigureAwait(false); } catch (Exception e) when ((exception = e) == null) { throw ExceptionUtilities.Unreachable; } finally { await pipe.Reader.CompleteAsync(exception).ConfigureAwait(false); } }, mustNotCancelToken); await Task.WhenAll(writerTask, readerTask).ConfigureAwait(false); return readerTask.Result; } private bool ReportUnexpectedException(Exception exception, CancellationToken cancellationToken) { if (exception is OperationCanceledException) { // It's a bug for a service to throw OCE based on a different cancellation token than it has received in the call. // The server side filter will report NFW in such scenario, so that the underlying issue can be fixed. // Do not treat this as a critical failure of the service for now and only fail in debug build. Debug.Assert(cancellationToken.IsCancellationRequested); return false; } // Do not report telemetry when the host is shutting down or the remote service threw an IO exception: if (IsHostShuttingDown || IsRemoteIOException(exception)) { return true; } // report telemetry event: Logger.Log(FunctionId.FeatureNotAvailable, $"{_serviceDescriptor.Moniker}: {exception.GetType()}: {exception.Message}"); return FatalError.ReportAndCatch(exception); } private bool IsHostShuttingDown => _shutdownCancellationService?.ShutdownToken.IsCancellationRequested == true; // TODO: we need https://github.com/microsoft/vs-streamjsonrpc/issues/468 to be implemented in order to check for IOException subtypes. private static bool IsRemoteIOException(Exception exception) => exception is RemoteInvocationException { ErrorData: CommonErrorData { TypeName: "System.IO.IOException" } }; private void OnUnexpectedException(Exception exception, CancellationToken cancellationToken) { // If the cancellation token passed to the remote call is not linked with the host shutdown cancellation token, // various non-cancellation exceptions may occur during the remote call. // Throw cancellation exception if the cancellation token is signaled. // If it is not then show info to the user that the service is not available dure to shutdown. cancellationToken.ThrowIfCancellationRequested(); if (_errorReportingService == null) { return; } // Show the error on the client. See https://github.com/dotnet/roslyn/issues/40476 for error classification details. // Based on the exception type and the state of the system we report one of the following: // - "Feature xyz is currently unavailable due to an intermittent error. Please try again later. Error message: '{1}'" (RemoteInvocationException: IOException) // - "Feature xyz is currently unavailable due to an internal error [Details]" (exception is RemoteInvocationException, MessagePackSerializationException, ConnectionLostException) // - "Feature xyz is currently unavailable since Visual Studio is shutting down" (connection exceptions during shutdown cancellation when cancellationToken is not signalled) // We expect all RPC calls to complete and not drop the connection. // ConnectionLostException indicates a bug that is likely thrown because the remote process crashed. // Currently, ConnectionLostException is also throw when the result of the RPC method fails to serialize // (see https://github.com/microsoft/vs-streamjsonrpc/issues/549) string message; Exception? internalException = null; var featureName = _serviceDescriptor.GetFeatureDisplayName(); if (IsRemoteIOException(exception)) { message = string.Format(RemoteWorkspacesResources.Feature_0_is_currently_unavailable_due_to_an_intermittent_error, featureName, exception.Message); } else if (IsHostShuttingDown) { message = string.Format(RemoteWorkspacesResources.Feature_0_is_currently_unavailable_host_shutting_down, featureName, _errorReportingService.HostDisplayName); } else { message = string.Format(RemoteWorkspacesResources.Feature_0_is_currently_unavailable_due_to_an_internal_error, featureName); internalException = exception; } _errorReportingService.ShowFeatureNotAvailableErrorInfo(message, internalException); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Pipelines; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Extensions; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.ServiceHub.Framework; using Microsoft.VisualStudio.Threading; using Roslyn.Utilities; using StreamJsonRpc; using StreamJsonRpc.Protocol; namespace Microsoft.CodeAnalysis.Remote { internal sealed class BrokeredServiceConnection<TService> : RemoteServiceConnection<TService> where TService : class { private readonly struct Rental : IDisposable { #pragma warning disable ISB002 // Avoid storing rentals in fields private readonly ServiceBrokerClient.Rental<TService> _proxyRental; #pragma warning restore public readonly TService Service; public Rental(ServiceBrokerClient.Rental<TService> proxyRental, TService service) { _proxyRental = proxyRental; Service = service; } public void Dispose() => _proxyRental.Dispose(); } private readonly IErrorReportingService? _errorReportingService; private readonly IRemoteHostClientShutdownCancellationService? _shutdownCancellationService; private readonly SolutionAssetStorage _solutionAssetStorage; private readonly ServiceDescriptor _serviceDescriptor; private readonly ServiceBrokerClient _serviceBrokerClient; private readonly RemoteServiceCallbackDispatcher.Handle _callbackHandle; private readonly IRemoteServiceCallbackDispatcher? _callbackDispatcher; public BrokeredServiceConnection( ServiceDescriptor serviceDescriptor, object? callbackTarget, IRemoteServiceCallbackDispatcher? callbackDispatcher, ServiceBrokerClient serviceBrokerClient, SolutionAssetStorage solutionAssetStorage, IErrorReportingService? errorReportingService, IRemoteHostClientShutdownCancellationService? shutdownCancellationService) { Contract.ThrowIfFalse((callbackDispatcher == null) == (serviceDescriptor.ClientInterface == null)); _serviceDescriptor = serviceDescriptor; _serviceBrokerClient = serviceBrokerClient; _solutionAssetStorage = solutionAssetStorage; _errorReportingService = errorReportingService; _shutdownCancellationService = shutdownCancellationService; _callbackDispatcher = callbackDispatcher; _callbackHandle = callbackDispatcher?.CreateHandle(callbackTarget) ?? default; } public override void Dispose() { _callbackHandle.Dispose(); } private async ValueTask<Rental> RentServiceAsync(CancellationToken cancellationToken) { // Make sure we are on the thread pool to avoid UI thread dependencies if external code uses ConfigureAwait(true) await TaskScheduler.Default; var options = new ServiceActivationOptions { ClientRpcTarget = _callbackDispatcher }; var proxyRental = await _serviceBrokerClient.GetProxyAsync<TService>(_serviceDescriptor, options, cancellationToken).ConfigureAwait(false); var service = proxyRental.Proxy; Contract.ThrowIfNull(service); return new Rental(proxyRental, service); } // no solution, no callback public override async ValueTask<bool> TryInvokeAsync(Func<TService, CancellationToken, ValueTask> invocation, CancellationToken cancellationToken) { try { using var rental = await RentServiceAsync(cancellationToken).ConfigureAwait(false); await invocation(rental.Service, cancellationToken).ConfigureAwait(false); return true; } catch (Exception exception) when (ReportUnexpectedException(exception, cancellationToken)) { OnUnexpectedException(exception, cancellationToken); return false; } } public override async ValueTask<Optional<TResult>> TryInvokeAsync<TResult>(Func<TService, CancellationToken, ValueTask<TResult>> invocation, CancellationToken cancellationToken) { try { using var rental = await RentServiceAsync(cancellationToken).ConfigureAwait(false); return await invocation(rental.Service, cancellationToken).ConfigureAwait(false); } catch (Exception exception) when (ReportUnexpectedException(exception, cancellationToken)) { OnUnexpectedException(exception, cancellationToken); return default; } } // no solution, callback public override async ValueTask<bool> TryInvokeAsync(Func<TService, RemoteServiceCallbackId, CancellationToken, ValueTask> invocation, CancellationToken cancellationToken) { Contract.ThrowIfFalse(_callbackDispatcher is not null); try { using var rental = await RentServiceAsync(cancellationToken).ConfigureAwait(false); await invocation(rental.Service, _callbackHandle.Id, cancellationToken).ConfigureAwait(false); return true; } catch (Exception exception) when (ReportUnexpectedException(exception, cancellationToken)) { OnUnexpectedException(exception, cancellationToken); return false; } } public override async ValueTask<Optional<TResult>> TryInvokeAsync<TResult>(Func<TService, RemoteServiceCallbackId, CancellationToken, ValueTask<TResult>> invocation, CancellationToken cancellationToken) { Contract.ThrowIfFalse(_callbackDispatcher is not null); try { using var rental = await RentServiceAsync(cancellationToken).ConfigureAwait(false); return await invocation(rental.Service, _callbackHandle.Id, cancellationToken).ConfigureAwait(false); } catch (Exception exception) when (ReportUnexpectedException(exception, cancellationToken)) { OnUnexpectedException(exception, cancellationToken); return default; } } // solution, no callback public override async ValueTask<bool> TryInvokeAsync(Solution solution, Func<TService, PinnedSolutionInfo, CancellationToken, ValueTask> invocation, CancellationToken cancellationToken) { try { using var scope = await _solutionAssetStorage.StoreAssetsAsync(solution, cancellationToken).ConfigureAwait(false); using var rental = await RentServiceAsync(cancellationToken).ConfigureAwait(false); await invocation(rental.Service, scope.SolutionInfo, cancellationToken).ConfigureAwait(false); return true; } catch (Exception exception) when (ReportUnexpectedException(exception, cancellationToken)) { OnUnexpectedException(exception, cancellationToken); return false; } } public override async ValueTask<Optional<TResult>> TryInvokeAsync<TResult>(Solution solution, Func<TService, PinnedSolutionInfo, CancellationToken, ValueTask<TResult>> invocation, CancellationToken cancellationToken) { try { using var scope = await _solutionAssetStorage.StoreAssetsAsync(solution, cancellationToken).ConfigureAwait(false); using var rental = await RentServiceAsync(cancellationToken).ConfigureAwait(false); return await invocation(rental.Service, scope.SolutionInfo, cancellationToken).ConfigureAwait(false); } catch (Exception exception) when (ReportUnexpectedException(exception, cancellationToken)) { OnUnexpectedException(exception, cancellationToken); return default; } } // project, no callback public override async ValueTask<bool> TryInvokeAsync(Project project, Func<TService, PinnedSolutionInfo, CancellationToken, ValueTask> invocation, CancellationToken cancellationToken) { try { using var scope = await _solutionAssetStorage.StoreAssetsAsync(project, cancellationToken).ConfigureAwait(false); using var rental = await RentServiceAsync(cancellationToken).ConfigureAwait(false); await invocation(rental.Service, scope.SolutionInfo, cancellationToken).ConfigureAwait(false); return true; } catch (Exception exception) when (ReportUnexpectedException(exception, cancellationToken)) { OnUnexpectedException(exception, cancellationToken); return false; } } public override async ValueTask<Optional<TResult>> TryInvokeAsync<TResult>(Project project, Func<TService, PinnedSolutionInfo, CancellationToken, ValueTask<TResult>> invocation, CancellationToken cancellationToken) { try { using var scope = await _solutionAssetStorage.StoreAssetsAsync(project, cancellationToken).ConfigureAwait(false); using var rental = await RentServiceAsync(cancellationToken).ConfigureAwait(false); return await invocation(rental.Service, scope.SolutionInfo, cancellationToken).ConfigureAwait(false); } catch (Exception exception) when (ReportUnexpectedException(exception, cancellationToken)) { OnUnexpectedException(exception, cancellationToken); return default; } } // solution, callback public override async ValueTask<bool> TryInvokeAsync(Solution solution, Func<TService, PinnedSolutionInfo, RemoteServiceCallbackId, CancellationToken, ValueTask> invocation, CancellationToken cancellationToken) { Contract.ThrowIfFalse(_callbackDispatcher is not null); try { using var scope = await _solutionAssetStorage.StoreAssetsAsync(solution, cancellationToken).ConfigureAwait(false); using var rental = await RentServiceAsync(cancellationToken).ConfigureAwait(false); await invocation(rental.Service, scope.SolutionInfo, _callbackHandle.Id, cancellationToken).ConfigureAwait(false); return true; } catch (Exception exception) when (ReportUnexpectedException(exception, cancellationToken)) { OnUnexpectedException(exception, cancellationToken); return false; } } public override async ValueTask<Optional<TResult>> TryInvokeAsync<TResult>(Solution solution, Func<TService, PinnedSolutionInfo, RemoteServiceCallbackId, CancellationToken, ValueTask<TResult>> invocation, CancellationToken cancellationToken) { Contract.ThrowIfFalse(_callbackDispatcher is not null); try { using var scope = await _solutionAssetStorage.StoreAssetsAsync(solution, cancellationToken).ConfigureAwait(false); using var rental = await RentServiceAsync(cancellationToken).ConfigureAwait(false); return await invocation(rental.Service, scope.SolutionInfo, _callbackHandle.Id, cancellationToken).ConfigureAwait(false); } catch (Exception exception) when (ReportUnexpectedException(exception, cancellationToken)) { OnUnexpectedException(exception, cancellationToken); return default; } } // project, callback public override async ValueTask<bool> TryInvokeAsync(Project project, Func<TService, PinnedSolutionInfo, RemoteServiceCallbackId, CancellationToken, ValueTask> invocation, CancellationToken cancellationToken) { Contract.ThrowIfFalse(_callbackDispatcher is not null); try { using var scope = await _solutionAssetStorage.StoreAssetsAsync(project, cancellationToken).ConfigureAwait(false); using var rental = await RentServiceAsync(cancellationToken).ConfigureAwait(false); await invocation(rental.Service, scope.SolutionInfo, _callbackHandle.Id, cancellationToken).ConfigureAwait(false); return true; } catch (Exception exception) when (ReportUnexpectedException(exception, cancellationToken)) { OnUnexpectedException(exception, cancellationToken); return false; } } public override async ValueTask<Optional<TResult>> TryInvokeAsync<TResult>(Project project, Func<TService, PinnedSolutionInfo, RemoteServiceCallbackId, CancellationToken, ValueTask<TResult>> invocation, CancellationToken cancellationToken) { Contract.ThrowIfFalse(_callbackDispatcher is not null); try { using var scope = await _solutionAssetStorage.StoreAssetsAsync(project, cancellationToken).ConfigureAwait(false); using var rental = await RentServiceAsync(cancellationToken).ConfigureAwait(false); return await invocation(rental.Service, scope.SolutionInfo, _callbackHandle.Id, cancellationToken).ConfigureAwait(false); } catch (Exception exception) when (ReportUnexpectedException(exception, cancellationToken)) { OnUnexpectedException(exception, cancellationToken); return default; } } // streaming public override async ValueTask<Optional<TResult>> TryInvokeAsync<TResult>( Func<TService, PipeWriter, CancellationToken, ValueTask> invocation, Func<PipeReader, CancellationToken, ValueTask<TResult>> reader, CancellationToken cancellationToken) { try { using var rental = await RentServiceAsync(cancellationToken).ConfigureAwait(false); return await InvokeStreamingServiceAsync(rental.Service, invocation, reader, cancellationToken).ConfigureAwait(false); } catch (Exception exception) when (ReportUnexpectedException(exception, cancellationToken)) { OnUnexpectedException(exception, cancellationToken); return default; } } public override async ValueTask<Optional<TResult>> TryInvokeAsync<TResult>( Solution solution, Func<TService, PinnedSolutionInfo, PipeWriter, CancellationToken, ValueTask> invocation, Func<PipeReader, CancellationToken, ValueTask<TResult>> reader, CancellationToken cancellationToken) { try { using var scope = await _solutionAssetStorage.StoreAssetsAsync(solution, cancellationToken).ConfigureAwait(false); using var rental = await RentServiceAsync(cancellationToken).ConfigureAwait(false); return await InvokeStreamingServiceAsync( rental.Service, (service, pipeWriter, cancellationToken) => invocation(service, scope.SolutionInfo, pipeWriter, cancellationToken), reader, cancellationToken).ConfigureAwait(false); } catch (Exception exception) when (ReportUnexpectedException(exception, cancellationToken)) { OnUnexpectedException(exception, cancellationToken); return default; } } public override async ValueTask<Optional<TResult>> TryInvokeAsync<TResult>( Project project, Func<TService, PinnedSolutionInfo, PipeWriter, CancellationToken, ValueTask> invocation, Func<PipeReader, CancellationToken, ValueTask<TResult>> reader, CancellationToken cancellationToken) { try { using var scope = await _solutionAssetStorage.StoreAssetsAsync(project, cancellationToken).ConfigureAwait(false); using var rental = await RentServiceAsync(cancellationToken).ConfigureAwait(false); return await InvokeStreamingServiceAsync( rental.Service, (service, pipeWriter, cancellationToken) => invocation(service, scope.SolutionInfo, pipeWriter, cancellationToken), reader, cancellationToken).ConfigureAwait(false); } catch (Exception exception) when (ReportUnexpectedException(exception, cancellationToken)) { OnUnexpectedException(exception, cancellationToken); return default; } } /// <param name="service">The service instance.</param> /// <param name="invocation">A callback to asynchronously write data. The callback is required to complete the /// <see cref="PipeWriter"/> except in cases where the callback throws an exception.</param> /// <param name="reader">A callback to asynchronously read data. The callback is allowed, but not required, to /// complete the <see cref="PipeReader"/>.</param> /// <param name="cancellationToken">A cancellation token the operation will observe.</param> internal static async ValueTask<TResult> InvokeStreamingServiceAsync<TResult>( TService service, Func<TService, PipeWriter, CancellationToken, ValueTask> invocation, Func<PipeReader, CancellationToken, ValueTask<TResult>> reader, CancellationToken cancellationToken) { // We can cancel at entry, but once the pipe operations are scheduled we rely on both operations running to // avoid deadlocks (the exception handler in 'writerTask' ensures progress is made in 'readerTask'). cancellationToken.ThrowIfCancellationRequested(); var mustNotCancelToken = CancellationToken.None; // After this point, the full cancellation sequence is as follows: // 1. 'cancellationToken' indicates cancellation is requested // 2. 'invocation' and 'readerTask' have cancellation requested // 3. 'invocation' stops writing to 'pipe.Writer' // 4. 'pipe.Writer' is completed // 5. 'readerTask' continues reading until EndOfStreamException (workaround for https://github.com/AArnott/Nerdbank.Streams/issues/361) // 6. 'pipe.Reader' is completed // 7. OperationCanceledException is thrown back to the caller var pipe = new Pipe(); // Create new tasks that both start executing, rather than invoking the delegates directly // to make sure both invocation and reader start executing and transfering data. var writerTask = Task.Run(async () => { try { await invocation(service, pipe.Writer, cancellationToken).ConfigureAwait(false); } catch (Exception e) { // Ensure that the writer is complete if an exception is thrown // before the writer is passed to the RPC proxy. Once it's passed to the proxy // the proxy should complete it as soon as the remote side completes it. await pipe.Writer.CompleteAsync(e).ConfigureAwait(false); throw; } }, mustNotCancelToken); var readerTask = Task.Run( async () => { Exception? exception = null; try { return await reader(pipe.Reader, cancellationToken).ConfigureAwait(false); } catch (Exception e) when ((exception = e) == null) { throw ExceptionUtilities.Unreachable; } finally { await pipe.Reader.CompleteAsync(exception).ConfigureAwait(false); } }, mustNotCancelToken); await Task.WhenAll(writerTask, readerTask).ConfigureAwait(false); return readerTask.Result; } private bool ReportUnexpectedException(Exception exception, CancellationToken cancellationToken) { if (exception is OperationCanceledException) { // It's a bug for a service to throw OCE based on a different cancellation token than it has received in the call. // The server side filter will report NFW in such scenario, so that the underlying issue can be fixed. // Do not treat this as a critical failure of the service for now and only fail in debug build. Debug.Assert(cancellationToken.IsCancellationRequested); return false; } // Do not report telemetry when the host is shutting down or the remote service threw an IO exception: if (IsHostShuttingDown || IsRemoteIOException(exception)) { return true; } // report telemetry event: Logger.Log(FunctionId.FeatureNotAvailable, $"{_serviceDescriptor.Moniker}: {exception.GetType()}: {exception.Message}"); return FatalError.ReportAndCatch(exception); } private bool IsHostShuttingDown => _shutdownCancellationService?.ShutdownToken.IsCancellationRequested == true; // TODO: we need https://github.com/microsoft/vs-streamjsonrpc/issues/468 to be implemented in order to check for IOException subtypes. private static bool IsRemoteIOException(Exception exception) => exception is RemoteInvocationException { ErrorData: CommonErrorData { TypeName: "System.IO.IOException" } }; private void OnUnexpectedException(Exception exception, CancellationToken cancellationToken) { // If the cancellation token passed to the remote call is not linked with the host shutdown cancellation token, // various non-cancellation exceptions may occur during the remote call. // Throw cancellation exception if the cancellation token is signaled. // If it is not then show info to the user that the service is not available dure to shutdown. cancellationToken.ThrowIfCancellationRequested(); if (_errorReportingService == null) { return; } // Show the error on the client. See https://github.com/dotnet/roslyn/issues/40476 for error classification details. // Based on the exception type and the state of the system we report one of the following: // - "Feature xyz is currently unavailable due to an intermittent error. Please try again later. Error message: '{1}'" (RemoteInvocationException: IOException) // - "Feature xyz is currently unavailable due to an internal error [Details]" (exception is RemoteInvocationException, MessagePackSerializationException, ConnectionLostException) // - "Feature xyz is currently unavailable since Visual Studio is shutting down" (connection exceptions during shutdown cancellation when cancellationToken is not signalled) // We expect all RPC calls to complete and not drop the connection. // ConnectionLostException indicates a bug that is likely thrown because the remote process crashed. // Currently, ConnectionLostException is also throw when the result of the RPC method fails to serialize // (see https://github.com/microsoft/vs-streamjsonrpc/issues/549) string message; Exception? internalException = null; var featureName = _serviceDescriptor.GetFeatureDisplayName(); if (IsRemoteIOException(exception)) { message = string.Format(RemoteWorkspacesResources.Feature_0_is_currently_unavailable_due_to_an_intermittent_error, featureName, exception.Message); } else if (IsHostShuttingDown) { message = string.Format(RemoteWorkspacesResources.Feature_0_is_currently_unavailable_host_shutting_down, featureName, _errorReportingService.HostDisplayName); } else { message = string.Format(RemoteWorkspacesResources.Feature_0_is_currently_unavailable_due_to_an_internal_error, featureName); internalException = exception; } _errorReportingService.ShowFeatureNotAvailableErrorInfo(message, internalException); } } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/Analyzers/Core/CodeFixes/UseConditionalExpression/UseConditionalExpressionHelpers.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Editing; using Microsoft.CodeAnalysis.LanguageServices; using static Microsoft.CodeAnalysis.UseConditionalExpression.UseConditionalExpressionHelpers; namespace Microsoft.CodeAnalysis.UseConditionalExpression { internal static class UseConditionalExpressionCodeFixHelpers { public static readonly SyntaxAnnotation SpecializedFormattingAnnotation = new(); public static SyntaxRemoveOptions GetRemoveOptions( ISyntaxFactsService syntaxFacts, SyntaxNode syntax) { var removeOptions = SyntaxGenerator.DefaultRemoveOptions; if (HasRegularCommentTrivia(syntaxFacts, syntax.GetLeadingTrivia())) { removeOptions |= SyntaxRemoveOptions.KeepLeadingTrivia; } if (HasRegularCommentTrivia(syntaxFacts, syntax.GetTrailingTrivia())) { removeOptions |= SyntaxRemoveOptions.KeepTrailingTrivia; } return removeOptions; } } }
// Licensed to the .NET Foundation under one or more agreements. // 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.Editing; using Microsoft.CodeAnalysis.LanguageServices; using static Microsoft.CodeAnalysis.UseConditionalExpression.UseConditionalExpressionHelpers; namespace Microsoft.CodeAnalysis.UseConditionalExpression { internal static class UseConditionalExpressionCodeFixHelpers { public static readonly SyntaxAnnotation SpecializedFormattingAnnotation = new(); public static SyntaxRemoveOptions GetRemoveOptions( ISyntaxFactsService syntaxFacts, SyntaxNode syntax) { var removeOptions = SyntaxGenerator.DefaultRemoveOptions; if (HasRegularCommentTrivia(syntaxFacts, syntax.GetLeadingTrivia())) { removeOptions |= SyntaxRemoveOptions.KeepLeadingTrivia; } if (HasRegularCommentTrivia(syntaxFacts, syntax.GetTrailingTrivia())) { removeOptions |= SyntaxRemoveOptions.KeepTrailingTrivia; } return removeOptions; } } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/Compilers/Server/VBCSCompiler/ServerDispatcher.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.IO.Pipes; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Globalization; using Microsoft.CodeAnalysis.CommandLine; using Microsoft.CodeAnalysis.Symbols; using Microsoft.CodeAnalysis.CSharp; namespace Microsoft.CodeAnalysis.CompilerServer { /// <summary> /// This class manages the connections, timeout and general scheduling of the client /// requests. /// </summary> internal sealed class ServerDispatcher { private enum State { /// <summary> /// Server running and accepting all requests /// </summary> Running, /// <summary> /// Server is in the process of shutting down. New connections will not be accepted. /// </summary> ShuttingDown, /// <summary> /// Server is done. /// </summary> Completed, } /// <summary> /// Default time the server will stay alive after the last request disconnects. /// </summary> internal static readonly TimeSpan DefaultServerKeepAlive = TimeSpan.FromMinutes(10); /// <summary> /// Time to delay after the last connection before initiating a garbage collection /// in the server. /// </summary> internal static readonly TimeSpan GCTimeout = TimeSpan.FromSeconds(30); private readonly ICompilerServerHost _compilerServerHost; private readonly ICompilerServerLogger _logger; private readonly IClientConnectionHost _clientConnectionHost; private readonly IDiagnosticListener _diagnosticListener; private State _state; private Task? _timeoutTask; private Task? _gcTask; private Task<IClientConnection>? _listenTask; private readonly List<Task<CompletionData>> _connectionList = new List<Task<CompletionData>>(); private TimeSpan? _keepAlive; private bool _keepAliveIsDefault; internal ServerDispatcher(ICompilerServerHost compilerServerHost, IClientConnectionHost clientConnectionHost, IDiagnosticListener? diagnosticListener = null) { _compilerServerHost = compilerServerHost; _logger = compilerServerHost.Logger; _clientConnectionHost = clientConnectionHost; _diagnosticListener = diagnosticListener ?? new EmptyDiagnosticListener(); } /// <summary> /// This function will accept and process new connections until an event causes /// the server to enter a passive shut down mode. For example if analyzers change /// or the keep alive timeout is hit. At which point this function will cease /// accepting new connections and wait for existing connections to complete before /// returning. /// </summary> public void ListenAndDispatchConnections(TimeSpan? keepAlive, CancellationToken cancellationToken = default) { _state = State.Running; _keepAlive = keepAlive; _keepAliveIsDefault = true; try { _clientConnectionHost.BeginListening(); ListenAndDispatchConnectionsCore(cancellationToken); } finally { _state = State.Completed; _gcTask = null; _timeoutTask = null; if (_clientConnectionHost.IsListening) { _clientConnectionHost.EndListening(); } if (_listenTask is not null) { // This type is responsible for cleaning up resources associated with _listenTask. Once EndListening // is complete this task is guaranteed to be either completed or have a task scheduled to complete // it. If it ran to completion we need to dispose of the value. if (!_listenTask.IsCompleted) { // Wait for the task to complete _listenTask.ContinueWith(_ => { }, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default) .Wait(CancellationToken.None); } if (_listenTask.Status == TaskStatus.RanToCompletion) { try { _listenTask.Result.Dispose(); } catch (Exception ex) { _logger.LogException(ex, $"Error disposing of {nameof(_listenTask)}"); } } } } _logger.Log($"End ListenAndDispatchConnections"); } public void ListenAndDispatchConnectionsCore(CancellationToken cancellationToken) { do { MaybeCreateListenTask(); MaybeCreateTimeoutTask(); MaybeCreateGCTask(); WaitForAnyCompletion(cancellationToken); CheckCompletedTasks(cancellationToken); } while (_connectionList.Count > 0 || _state == State.Running); } private void CheckCompletedTasks(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { ChangeToShuttingDown("Server cancellation"); Debug.Assert(_gcTask is null); Debug.Assert(_timeoutTask is null); } if (_listenTask?.IsCompleted == true) { _diagnosticListener.ConnectionReceived(); var connectionTask = ProcessClientConnectionAsync( _compilerServerHost, _listenTask, allowCompilationRequests: _state == State.Running, cancellationToken); _connectionList.Add(connectionTask); // Timeout and GC are only done when there are no active connections. Now that we have a new // connection cancel out these tasks. _timeoutTask = null; _gcTask = null; _listenTask = null; } if (_timeoutTask?.IsCompleted == true) { _diagnosticListener.KeepAliveReached(); ChangeToShuttingDown("Keep alive hit"); } if (_gcTask?.IsCompleted == true) { RunGC(); } HandleCompletedConnections(); } /// <summary> /// The server farms out work to Task values and this method needs to wait until at least one of them /// has completed. /// </summary> private void WaitForAnyCompletion(CancellationToken cancellationToken) { var all = new List<Task>(); all.AddRange(_connectionList); AddNonNull(_timeoutTask); AddNonNull(_listenTask); AddNonNull(_gcTask); try { Task.WaitAny(all.ToArray(), cancellationToken); } catch (OperationCanceledException) { // Thrown when the provided cancellationToken is cancelled. This is handled in the caller, // here it just serves to break out of the WaitAny call. } void AddNonNull(Task? task) { if (task is object) { all.Add(task); } } } private void ChangeToShuttingDown(string reason) { if (_state == State.ShuttingDown) { return; } _logger.Log($"Shutting down server: {reason}"); Debug.Assert(_state == State.Running); Debug.Assert(_clientConnectionHost.IsListening); _state = State.ShuttingDown; _timeoutTask = null; _gcTask = null; } private void RunGC() { _gcTask = null; GC.GetTotalMemory(forceFullCollection: true); } private void MaybeCreateListenTask() { if (_listenTask is null) { _listenTask = _clientConnectionHost.GetNextClientConnectionAsync(); } } private void MaybeCreateTimeoutTask() { // If there are no active clients running then the server needs to be in a timeout mode. if (_state == State.Running && _connectionList.Count == 0 && _timeoutTask is null && _keepAlive.HasValue) { Debug.Assert(_listenTask != null); _timeoutTask = Task.Delay(_keepAlive.Value); } } private void MaybeCreateGCTask() { if (_state == State.Running && _connectionList.Count == 0 && _gcTask is null) { _gcTask = Task.Delay(GCTimeout); } } /// <summary> /// Checks the completed connection objects and updates the server state based on their /// results. /// </summary> private void HandleCompletedConnections() { var shutdown = false; var i = 0; while (i < _connectionList.Count) { var current = _connectionList[i]; if (!current.IsCompleted) { i++; continue; } _connectionList.RemoveAt(i); // These task should never fail. Unexpected errors will be caught and translated into // a RequestError message Debug.Assert(current.Status == TaskStatus.RanToCompletion); var completionData = current.Result; switch (completionData.Reason) { case CompletionReason.RequestCompleted: _logger.Log("Client request completed"); if (completionData.NewKeepAlive is { } keepAlive) { _logger.Log($"Client changed keep alive to {keepAlive}"); ChangeKeepAlive(keepAlive); } if (completionData.ShutdownRequest) { _logger.Log("Client requested shutdown"); shutdown = true; } break; case CompletionReason.RequestError: _logger.LogError("Client request failed"); shutdown = true; break; default: _logger.LogError("Unexpected enum value"); shutdown = true; break; } _diagnosticListener.ConnectionCompleted(completionData); } if (shutdown) { ChangeToShuttingDown("Error handling client connection"); } } private void ChangeKeepAlive(TimeSpan keepAlive) { if (_keepAliveIsDefault || !_keepAlive.HasValue || keepAlive > _keepAlive.Value) { _keepAlive = keepAlive; _keepAliveIsDefault = false; _diagnosticListener.UpdateKeepAlive(keepAlive); } } internal static async Task<CompletionData> ProcessClientConnectionAsync( ICompilerServerHost compilerServerHost, Task<IClientConnection> clientStreamTask, bool allowCompilationRequests, CancellationToken cancellationToken) { var clientHandler = new ClientConnectionHandler(compilerServerHost); return await clientHandler.ProcessAsync(clientStreamTask, allowCompilationRequests, cancellationToken).ConfigureAwait(false); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.IO.Pipes; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Globalization; using Microsoft.CodeAnalysis.CommandLine; using Microsoft.CodeAnalysis.Symbols; using Microsoft.CodeAnalysis.CSharp; namespace Microsoft.CodeAnalysis.CompilerServer { /// <summary> /// This class manages the connections, timeout and general scheduling of the client /// requests. /// </summary> internal sealed class ServerDispatcher { private enum State { /// <summary> /// Server running and accepting all requests /// </summary> Running, /// <summary> /// Server is in the process of shutting down. New connections will not be accepted. /// </summary> ShuttingDown, /// <summary> /// Server is done. /// </summary> Completed, } /// <summary> /// Default time the server will stay alive after the last request disconnects. /// </summary> internal static readonly TimeSpan DefaultServerKeepAlive = TimeSpan.FromMinutes(10); /// <summary> /// Time to delay after the last connection before initiating a garbage collection /// in the server. /// </summary> internal static readonly TimeSpan GCTimeout = TimeSpan.FromSeconds(30); private readonly ICompilerServerHost _compilerServerHost; private readonly ICompilerServerLogger _logger; private readonly IClientConnectionHost _clientConnectionHost; private readonly IDiagnosticListener _diagnosticListener; private State _state; private Task? _timeoutTask; private Task? _gcTask; private Task<IClientConnection>? _listenTask; private readonly List<Task<CompletionData>> _connectionList = new List<Task<CompletionData>>(); private TimeSpan? _keepAlive; private bool _keepAliveIsDefault; internal ServerDispatcher(ICompilerServerHost compilerServerHost, IClientConnectionHost clientConnectionHost, IDiagnosticListener? diagnosticListener = null) { _compilerServerHost = compilerServerHost; _logger = compilerServerHost.Logger; _clientConnectionHost = clientConnectionHost; _diagnosticListener = diagnosticListener ?? new EmptyDiagnosticListener(); } /// <summary> /// This function will accept and process new connections until an event causes /// the server to enter a passive shut down mode. For example if analyzers change /// or the keep alive timeout is hit. At which point this function will cease /// accepting new connections and wait for existing connections to complete before /// returning. /// </summary> public void ListenAndDispatchConnections(TimeSpan? keepAlive, CancellationToken cancellationToken = default) { _state = State.Running; _keepAlive = keepAlive; _keepAliveIsDefault = true; try { _clientConnectionHost.BeginListening(); ListenAndDispatchConnectionsCore(cancellationToken); } finally { _state = State.Completed; _gcTask = null; _timeoutTask = null; if (_clientConnectionHost.IsListening) { _clientConnectionHost.EndListening(); } if (_listenTask is not null) { // This type is responsible for cleaning up resources associated with _listenTask. Once EndListening // is complete this task is guaranteed to be either completed or have a task scheduled to complete // it. If it ran to completion we need to dispose of the value. if (!_listenTask.IsCompleted) { // Wait for the task to complete _listenTask.ContinueWith(_ => { }, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default) .Wait(CancellationToken.None); } if (_listenTask.Status == TaskStatus.RanToCompletion) { try { _listenTask.Result.Dispose(); } catch (Exception ex) { _logger.LogException(ex, $"Error disposing of {nameof(_listenTask)}"); } } } } _logger.Log($"End ListenAndDispatchConnections"); } public void ListenAndDispatchConnectionsCore(CancellationToken cancellationToken) { do { MaybeCreateListenTask(); MaybeCreateTimeoutTask(); MaybeCreateGCTask(); WaitForAnyCompletion(cancellationToken); CheckCompletedTasks(cancellationToken); } while (_connectionList.Count > 0 || _state == State.Running); } private void CheckCompletedTasks(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { ChangeToShuttingDown("Server cancellation"); Debug.Assert(_gcTask is null); Debug.Assert(_timeoutTask is null); } if (_listenTask?.IsCompleted == true) { _diagnosticListener.ConnectionReceived(); var connectionTask = ProcessClientConnectionAsync( _compilerServerHost, _listenTask, allowCompilationRequests: _state == State.Running, cancellationToken); _connectionList.Add(connectionTask); // Timeout and GC are only done when there are no active connections. Now that we have a new // connection cancel out these tasks. _timeoutTask = null; _gcTask = null; _listenTask = null; } if (_timeoutTask?.IsCompleted == true) { _diagnosticListener.KeepAliveReached(); ChangeToShuttingDown("Keep alive hit"); } if (_gcTask?.IsCompleted == true) { RunGC(); } HandleCompletedConnections(); } /// <summary> /// The server farms out work to Task values and this method needs to wait until at least one of them /// has completed. /// </summary> private void WaitForAnyCompletion(CancellationToken cancellationToken) { var all = new List<Task>(); all.AddRange(_connectionList); AddNonNull(_timeoutTask); AddNonNull(_listenTask); AddNonNull(_gcTask); try { Task.WaitAny(all.ToArray(), cancellationToken); } catch (OperationCanceledException) { // Thrown when the provided cancellationToken is cancelled. This is handled in the caller, // here it just serves to break out of the WaitAny call. } void AddNonNull(Task? task) { if (task is object) { all.Add(task); } } } private void ChangeToShuttingDown(string reason) { if (_state == State.ShuttingDown) { return; } _logger.Log($"Shutting down server: {reason}"); Debug.Assert(_state == State.Running); Debug.Assert(_clientConnectionHost.IsListening); _state = State.ShuttingDown; _timeoutTask = null; _gcTask = null; } private void RunGC() { _gcTask = null; GC.GetTotalMemory(forceFullCollection: true); } private void MaybeCreateListenTask() { if (_listenTask is null) { _listenTask = _clientConnectionHost.GetNextClientConnectionAsync(); } } private void MaybeCreateTimeoutTask() { // If there are no active clients running then the server needs to be in a timeout mode. if (_state == State.Running && _connectionList.Count == 0 && _timeoutTask is null && _keepAlive.HasValue) { Debug.Assert(_listenTask != null); _timeoutTask = Task.Delay(_keepAlive.Value); } } private void MaybeCreateGCTask() { if (_state == State.Running && _connectionList.Count == 0 && _gcTask is null) { _gcTask = Task.Delay(GCTimeout); } } /// <summary> /// Checks the completed connection objects and updates the server state based on their /// results. /// </summary> private void HandleCompletedConnections() { var shutdown = false; var i = 0; while (i < _connectionList.Count) { var current = _connectionList[i]; if (!current.IsCompleted) { i++; continue; } _connectionList.RemoveAt(i); // These task should never fail. Unexpected errors will be caught and translated into // a RequestError message Debug.Assert(current.Status == TaskStatus.RanToCompletion); var completionData = current.Result; switch (completionData.Reason) { case CompletionReason.RequestCompleted: _logger.Log("Client request completed"); if (completionData.NewKeepAlive is { } keepAlive) { _logger.Log($"Client changed keep alive to {keepAlive}"); ChangeKeepAlive(keepAlive); } if (completionData.ShutdownRequest) { _logger.Log("Client requested shutdown"); shutdown = true; } break; case CompletionReason.RequestError: _logger.LogError("Client request failed"); shutdown = true; break; default: _logger.LogError("Unexpected enum value"); shutdown = true; break; } _diagnosticListener.ConnectionCompleted(completionData); } if (shutdown) { ChangeToShuttingDown("Error handling client connection"); } } private void ChangeKeepAlive(TimeSpan keepAlive) { if (_keepAliveIsDefault || !_keepAlive.HasValue || keepAlive > _keepAlive.Value) { _keepAlive = keepAlive; _keepAliveIsDefault = false; _diagnosticListener.UpdateKeepAlive(keepAlive); } } internal static async Task<CompletionData> ProcessClientConnectionAsync( ICompilerServerHost compilerServerHost, Task<IClientConnection> clientStreamTask, bool allowCompilationRequests, CancellationToken cancellationToken) { var clientHandler = new ClientConnectionHandler(compilerServerHost); return await clientHandler.ProcessAsync(clientStreamTask, allowCompilationRequests, cancellationToken).ConfigureAwait(false); } } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/Features/Core/Portable/AddImport/SymbolReferenceFinder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Packaging; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.SymbolSearch; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.Shared.Utilities.EditorBrowsableHelpers; namespace Microsoft.CodeAnalysis.AddImport { internal abstract partial class AbstractAddImportFeatureService<TSimpleNameSyntax> { private partial class SymbolReferenceFinder { private const string AttributeSuffix = nameof(Attribute); private readonly string _diagnosticId; private readonly Document _document; private readonly SemanticModel _semanticModel; private readonly ISet<INamespaceSymbol> _namespacesInScope; private readonly ISyntaxFactsService _syntaxFacts; private readonly AbstractAddImportFeatureService<TSimpleNameSyntax> _owner; private readonly SyntaxNode _node; private readonly ISymbolSearchService _symbolSearchService; private readonly bool _searchReferenceAssemblies; private readonly ImmutableArray<PackageSource> _packageSources; public SymbolReferenceFinder( AbstractAddImportFeatureService<TSimpleNameSyntax> owner, Document document, SemanticModel semanticModel, string diagnosticId, SyntaxNode node, ISymbolSearchService symbolSearchService, bool searchReferenceAssemblies, ImmutableArray<PackageSource> packageSources, CancellationToken cancellationToken) { _owner = owner; _document = document; _semanticModel = semanticModel; _diagnosticId = diagnosticId; _node = node; _symbolSearchService = symbolSearchService; _searchReferenceAssemblies = searchReferenceAssemblies; _packageSources = packageSources; if (_searchReferenceAssemblies || packageSources.Length > 0) { Contract.ThrowIfNull(symbolSearchService); } _syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); _namespacesInScope = GetNamespacesInScope(cancellationToken); } private ISet<INamespaceSymbol> GetNamespacesInScope(CancellationToken cancellationToken) { // Add all the namespaces brought in by imports/usings. var set = _owner.GetImportNamespacesInScope(_semanticModel, _node, cancellationToken); // Also add all the namespaces we're contained in. We don't want // to add imports for these namespaces either. for (var containingNamespace = _semanticModel.GetEnclosingNamespace(_node.SpanStart, cancellationToken); containingNamespace != null; containingNamespace = containingNamespace.ContainingNamespace) { set.Add(MapToCompilationNamespaceIfPossible(containingNamespace)); } return set; } private INamespaceSymbol MapToCompilationNamespaceIfPossible(INamespaceSymbol containingNamespace) => _semanticModel.Compilation.GetCompilationNamespace(containingNamespace) ?? containingNamespace; internal Task<ImmutableArray<SymbolReference>> FindInAllSymbolsInStartingProjectAsync( bool exact, CancellationToken cancellationToken) { var searchScope = new AllSymbolsProjectSearchScope( _owner, _document.Project, exact, cancellationToken); return DoAsync(searchScope); } internal Task<ImmutableArray<SymbolReference>> FindInSourceSymbolsInProjectAsync( ConcurrentDictionary<Project, AsyncLazy<IAssemblySymbol>> projectToAssembly, Project project, bool exact, CancellationToken cancellationToken) { var searchScope = new SourceSymbolsProjectSearchScope( _owner, projectToAssembly, project, exact, cancellationToken); return DoAsync(searchScope); } internal Task<ImmutableArray<SymbolReference>> FindInMetadataSymbolsAsync( IAssemblySymbol assembly, ProjectId assemblyProjectId, PortableExecutableReference metadataReference, bool exact, CancellationToken cancellationToken) { var searchScope = new MetadataSymbolsSearchScope( _owner, _document.Project.Solution, assembly, assemblyProjectId, metadataReference, exact, cancellationToken); return DoAsync(searchScope); } private async Task<ImmutableArray<SymbolReference>> DoAsync(SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); // Spin off tasks to do all our searching in parallel using var _1 = ArrayBuilder<Task<ImmutableArray<SymbolReference>>>.GetInstance(out var tasks); tasks.Add(GetReferencesForMatchingTypesAsync(searchScope)); tasks.Add(GetReferencesForMatchingNamespacesAsync(searchScope)); tasks.Add(GetReferencesForMatchingFieldsAndPropertiesAsync(searchScope)); tasks.Add(GetReferencesForMatchingExtensionMethodsAsync(searchScope)); // Searching for things like "Add" (for collection initializers) and "Select" // (for extension methods) should only be done when doing an 'exact' search. // We should not do fuzzy searches for these names. In this case it's not // like the user was writing Add or Select, but instead we're looking for // viable symbols with those names to make a collection initializer or // query expression valid. if (searchScope.Exact) { tasks.Add(GetReferencesForCollectionInitializerMethodsAsync(searchScope)); tasks.Add(GetReferencesForQueryPatternsAsync(searchScope)); tasks.Add(GetReferencesForDeconstructAsync(searchScope)); tasks.Add(GetReferencesForGetAwaiterAsync(searchScope)); tasks.Add(GetReferencesForGetEnumeratorAsync(searchScope)); tasks.Add(GetReferencesForGetAsyncEnumeratorAsync(searchScope)); } await Task.WhenAll(tasks).ConfigureAwait(false); searchScope.CancellationToken.ThrowIfCancellationRequested(); using var _2 = ArrayBuilder<SymbolReference>.GetInstance(out var allReferences); foreach (var task in tasks) { var taskResult = await task.ConfigureAwait(false); allReferences.AddRange(taskResult); } return DeDupeAndSortReferences(allReferences.ToImmutable()); } private ImmutableArray<SymbolReference> DeDupeAndSortReferences(ImmutableArray<SymbolReference> allReferences) { return allReferences .Distinct() .Where(NotNull) .Where(NotGlobalNamespace) .OrderBy((r1, r2) => r1.CompareTo(_document, r2)) .ToImmutableArray(); } private static void CalculateContext( TSimpleNameSyntax nameNode, ISyntaxFactsService syntaxFacts, out string name, out int arity, out bool inAttributeContext, out bool hasIncompleteParentMember, out bool looksGeneric) { // Has to be a simple identifier or generic name. syntaxFacts.GetNameAndArityOfSimpleName(nameNode, out name, out arity); inAttributeContext = syntaxFacts.IsAttributeName(nameNode); hasIncompleteParentMember = nameNode?.Parent?.RawKind == syntaxFacts.SyntaxKinds.IncompleteMember; looksGeneric = syntaxFacts.LooksGeneric(nameNode); } /// <summary> /// Searches for types that match the name the user has written. Returns <see cref="SymbolReference"/>s /// to the <see cref="INamespaceSymbol"/>s or <see cref="INamedTypeSymbol"/>s those types are /// contained in. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForMatchingTypesAsync(SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (!_owner.CanAddImportForType(_diagnosticId, _node, out var nameNode)) { return ImmutableArray<SymbolReference>.Empty; } CalculateContext( nameNode, _syntaxFacts, out var name, out var arity, out var inAttributeContext, out var hasIncompleteParentMember, out var looksGeneric); if (ExpressionBinds(nameNode, checkForExtensionMethods: false, cancellationToken: searchScope.CancellationToken)) { // If the expression bound, there's nothing to do. return ImmutableArray<SymbolReference>.Empty; } var symbols = await searchScope.FindDeclarationsAsync(name, nameNode, SymbolFilter.Type).ConfigureAwait(false); // also lookup type symbols with the "Attribute" suffix if necessary. if (inAttributeContext) { var attributeSymbols = await searchScope.FindDeclarationsAsync(name + AttributeSuffix, nameNode, SymbolFilter.Type).ConfigureAwait(false); symbols = symbols.AddRange( attributeSymbols.Select(r => r.WithDesiredName(r.DesiredName.GetWithoutAttributeSuffix(isCaseSensitive: false)))); } var typeSymbols = OfType<ITypeSymbol>(symbols); var options = await _document.GetOptionsAsync(searchScope.CancellationToken).ConfigureAwait(false); var hideAdvancedMembers = options.GetOption(CompletionOptions.HideAdvancedMembers); var editorBrowserInfo = new EditorBrowsableInfo(_semanticModel.Compilation); // Only keep symbols which are accessible from the current location and that are allowed by the current // editor browsable rules. var accessibleTypeSymbols = typeSymbols.WhereAsArray( s => ArityAccessibilityAndAttributeContextAreCorrect(s.Symbol, arity, inAttributeContext, hasIncompleteParentMember, looksGeneric) && s.Symbol.IsEditorBrowsable(hideAdvancedMembers, _semanticModel.Compilation, editorBrowserInfo)); // These types may be contained within namespaces, or they may be nested // inside generic types. Record these namespaces/types if it would be // legal to add imports for them. var typesContainedDirectlyInNamespaces = accessibleTypeSymbols.WhereAsArray(s => s.Symbol.ContainingSymbol is INamespaceSymbol); var typesContainedDirectlyInTypes = accessibleTypeSymbols.WhereAsArray(s => s.Symbol.ContainingType != null); var namespaceReferences = GetNamespaceSymbolReferences(searchScope, typesContainedDirectlyInNamespaces.SelectAsArray(r => r.WithSymbol(r.Symbol.ContainingNamespace))); var typeReferences = typesContainedDirectlyInTypes.SelectAsArray( r => searchScope.CreateReference(r.WithSymbol(r.Symbol.ContainingType))); return namespaceReferences.Concat(typeReferences); } private bool ArityAccessibilityAndAttributeContextAreCorrect( ITypeSymbol symbol, int arity, bool inAttributeContext, bool hasIncompleteParentMember, bool looksGeneric) { if (inAttributeContext && !symbol.IsAttribute()) { return false; } if (!symbol.IsAccessibleWithin(_semanticModel.Compilation.Assembly)) { return false; } if (looksGeneric && symbol.GetTypeArguments().Length == 0) { return false; } return arity == 0 || symbol.GetArity() == arity || hasIncompleteParentMember; } /// <summary> /// Searches for namespaces that match the name the user has written. Returns <see cref="SymbolReference"/>s /// to the <see cref="INamespaceSymbol"/>s those namespaces are contained in. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForMatchingNamespacesAsync( SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (_owner.CanAddImportForNamespace(_diagnosticId, _node, out var nameNode)) { _syntaxFacts.GetNameAndArityOfSimpleName(nameNode, out var name, out var arity); if (arity == 0 && !ExpressionBinds(nameNode, checkForExtensionMethods: false, cancellationToken: searchScope.CancellationToken)) { var symbols = await searchScope.FindDeclarationsAsync(name, nameNode, SymbolFilter.Namespace).ConfigureAwait(false); var namespaceSymbols = OfType<INamespaceSymbol>(symbols); var containingNamespaceSymbols = OfType<INamespaceSymbol>(symbols).SelectAsArray(s => s.WithSymbol(s.Symbol.ContainingNamespace)); return GetNamespaceSymbolReferences(searchScope, containingNamespaceSymbols); } } return ImmutableArray<SymbolReference>.Empty; } /// <summary> /// Specialized finder for the "Color Color" case. Used when we have "Color.Black" and "Color" /// bound to a Field/Property, but not a type. In this case, we want to look for namespaces /// containing 'Color' as if we import them it can resolve this issue. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForMatchingFieldsAndPropertiesAsync( SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (_owner.CanAddImportForMethod(_diagnosticId, _syntaxFacts, _node, out var nameNode) && nameNode != null) { // We have code like "Color.Black". "Color" bound to a 'Color Color' property, and // 'Black' did not bind. We want to find a type called 'Color' that will actually // allow 'Black' to bind. var syntaxFacts = _document.GetLanguageService<ISyntaxFactsService>(); if (syntaxFacts.IsNameOfSimpleMemberAccessExpression(nameNode) || syntaxFacts.IsNameOfMemberBindingExpression(nameNode)) { var expression = syntaxFacts.IsNameOfSimpleMemberAccessExpression(nameNode) ? syntaxFacts.GetExpressionOfMemberAccessExpression(nameNode.Parent, allowImplicitTarget: true) : syntaxFacts.GetTargetOfMemberBinding(nameNode.Parent); if (expression is TSimpleNameSyntax simpleName) { // Check if the expression before the dot binds to a property or field. var symbol = _semanticModel.GetSymbolInfo(expression, searchScope.CancellationToken).GetAnySymbol(); if (symbol?.Kind is SymbolKind.Property or SymbolKind.Field) { // Check if we have the 'Color Color' case. var propertyOrFieldType = symbol.GetSymbolType(); if (propertyOrFieldType is INamedTypeSymbol propertyType && Equals(propertyType.Name, symbol.Name)) { // Try to look up 'Color' as a type. var symbolResults = await searchScope.FindDeclarationsAsync( symbol.Name, simpleName, SymbolFilter.Type).ConfigureAwait(false); // Return results that have accessible members. var namedTypeSymbols = OfType<INamedTypeSymbol>(symbolResults); var name = nameNode.GetFirstToken().ValueText; var namespaceResults = namedTypeSymbols.WhereAsArray(sr => HasAccessibleStaticFieldOrProperty(sr.Symbol, name)) .SelectAsArray(sr => sr.WithSymbol(sr.Symbol.ContainingNamespace)); return GetNamespaceSymbolReferences(searchScope, namespaceResults); } } } } } return ImmutableArray<SymbolReference>.Empty; } private bool HasAccessibleStaticFieldOrProperty(INamedTypeSymbol namedType, string fieldOrPropertyName) { return namedType.GetMembers(fieldOrPropertyName) .Any(m => (m is IFieldSymbol || m is IPropertySymbol) && m.IsStatic && m.IsAccessibleWithin(_semanticModel.Compilation.Assembly)); } /// <summary> /// Searches for extension methods that match the name the user has written. Returns /// <see cref="SymbolReference"/>s to the <see cref="INamespaceSymbol"/>s that contain /// the static classes that those extension methods are contained in. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForMatchingExtensionMethodsAsync(SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (_owner.CanAddImportForMethod(_diagnosticId, _syntaxFacts, _node, out var nameNode) && nameNode != null) { searchScope.CancellationToken.ThrowIfCancellationRequested(); // See if the name binds. If it does, there's nothing further we need to do. if (!ExpressionBinds(nameNode, checkForExtensionMethods: true, cancellationToken: searchScope.CancellationToken)) { _syntaxFacts.GetNameAndArityOfSimpleName(nameNode, out var name, out var arity); if (name != null) { var symbols = await searchScope.FindDeclarationsAsync(name, nameNode, SymbolFilter.Member).ConfigureAwait(false); var methodSymbols = OfType<IMethodSymbol>(symbols); var extensionMethodSymbols = GetViableExtensionMethods( methodSymbols, nameNode.Parent, searchScope.CancellationToken); var namespaceSymbols = extensionMethodSymbols.SelectAsArray(s => s.WithSymbol(s.Symbol.ContainingNamespace)); return GetNamespaceSymbolReferences(searchScope, namespaceSymbols); } } } return ImmutableArray<SymbolReference>.Empty; } private ImmutableArray<SymbolResult<IMethodSymbol>> GetViableExtensionMethods( ImmutableArray<SymbolResult<IMethodSymbol>> methodSymbols, SyntaxNode expression, CancellationToken cancellationToken) { return GetViableExtensionMethodsWorker(methodSymbols).WhereAsArray( s => _owner.IsViableExtensionMethod(s.Symbol, expression, _semanticModel, _syntaxFacts, cancellationToken)); } private ImmutableArray<SymbolResult<IMethodSymbol>> GetViableExtensionMethods( ImmutableArray<SymbolResult<IMethodSymbol>> methodSymbols, ITypeSymbol typeSymbol) { return GetViableExtensionMethodsWorker(methodSymbols).WhereAsArray( s => IsViableExtensionMethod(s.Symbol, typeSymbol)); } private ImmutableArray<SymbolResult<IMethodSymbol>> GetViableExtensionMethodsWorker( ImmutableArray<SymbolResult<IMethodSymbol>> methodSymbols) { return methodSymbols.WhereAsArray( s => s.Symbol.IsExtensionMethod && s.Symbol.IsAccessibleWithin(_semanticModel.Compilation.Assembly)); } /// <summary> /// Searches for extension methods exactly called 'Add'. Returns /// <see cref="SymbolReference"/>s to the <see cref="INamespaceSymbol"/>s that contain /// the static classes that those extension methods are contained in. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForCollectionInitializerMethodsAsync(SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (_owner.CanAddImportForMethod(_diagnosticId, _syntaxFacts, _node, out _) && !_syntaxFacts.IsSimpleName(_node) && _owner.IsAddMethodContext(_node, _semanticModel)) { var symbols = await searchScope.FindDeclarationsAsync( nameof(IList.Add), nameNode: null, filter: SymbolFilter.Member).ConfigureAwait(false); // Note: there is no desiredName for these search results. We're searching for // extension methods called "Add", but we have no intention of renaming any // of the existing user code to that name. var methodSymbols = OfType<IMethodSymbol>(symbols).SelectAsArray(s => s.WithDesiredName(null)); var viableMethods = GetViableExtensionMethods( methodSymbols, _node.Parent, searchScope.CancellationToken); return GetNamespaceSymbolReferences(searchScope, viableMethods.SelectAsArray(m => m.WithSymbol(m.Symbol.ContainingNamespace))); } return ImmutableArray<SymbolReference>.Empty; } /// <summary> /// Searches for extension methods exactly called 'Select'. Returns /// <see cref="SymbolReference"/>s to the <see cref="INamespaceSymbol"/>s that contain /// the static classes that those extension methods are contained in. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForQueryPatternsAsync(SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (_owner.CanAddImportForQuery(_diagnosticId, _node)) { var type = _owner.GetQueryClauseInfo(_semanticModel, _node, searchScope.CancellationToken); if (type != null) { // find extension methods named "Select" return await GetReferencesForExtensionMethodAsync( searchScope, nameof(Enumerable.Select), type).ConfigureAwait(false); } } return ImmutableArray<SymbolReference>.Empty; } /// <summary> /// Searches for extension methods exactly called 'GetAwaiter'. Returns /// <see cref="SymbolReference"/>s to the <see cref="INamespaceSymbol"/>s that contain /// the static classes that those extension methods are contained in. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForGetAwaiterAsync(SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (_owner.CanAddImportForGetAwaiter(_diagnosticId, _syntaxFacts, _node)) { var type = GetAwaitInfo(_semanticModel, _syntaxFacts, _node); if (type != null) { return await GetReferencesForExtensionMethodAsync(searchScope, WellKnownMemberNames.GetAwaiter, type, m => m.IsValidGetAwaiter()).ConfigureAwait(false); } } return ImmutableArray<SymbolReference>.Empty; } /// <summary> /// Searches for extension methods exactly called 'GetEnumerator'. Returns /// <see cref="SymbolReference"/>s to the <see cref="INamespaceSymbol"/>s that contain /// the static classes that those extension methods are contained in. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForGetEnumeratorAsync(SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (_owner.CanAddImportForGetEnumerator(_diagnosticId, _syntaxFacts, _node)) { var type = GetCollectionExpressionType(_semanticModel, _syntaxFacts, _node); if (type != null) { return await GetReferencesForExtensionMethodAsync(searchScope, WellKnownMemberNames.GetEnumeratorMethodName, type, m => m.IsValidGetEnumerator()).ConfigureAwait(false); } } return ImmutableArray<SymbolReference>.Empty; } /// <summary> /// Searches for extension methods exactly called 'GetAsyncEnumerator'. Returns /// <see cref="SymbolReference"/>s to the <see cref="INamespaceSymbol"/>s that contain /// the static classes that those extension methods are contained in. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForGetAsyncEnumeratorAsync(SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (_owner.CanAddImportForGetAsyncEnumerator(_diagnosticId, _syntaxFacts, _node)) { var type = GetCollectionExpressionType(_semanticModel, _syntaxFacts, _node); if (type != null) { return await GetReferencesForExtensionMethodAsync(searchScope, WellKnownMemberNames.GetAsyncEnumeratorMethodName, type, m => m.IsValidGetAsyncEnumerator()).ConfigureAwait(false); } } return ImmutableArray<SymbolReference>.Empty; } /// <summary> /// Searches for extension methods exactly called 'Deconstruct'. Returns /// <see cref="SymbolReference"/>s to the <see cref="INamespaceSymbol"/>s that contain /// the static classes that those extension methods are contained in. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForDeconstructAsync(SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (_owner.CanAddImportForDeconstruct(_diagnosticId, _node)) { var type = _owner.GetDeconstructInfo(_semanticModel, _node, searchScope.CancellationToken); if (type != null) { // Note: we could check that the extension methods have the right number of out-params. // But that would involve figuring out what we're trying to deconstruct into. For now // we'll just be permissive, with the assumption that there won't be that many matching // 'Deconstruct' extension methods for the type of node that we're on. return await GetReferencesForExtensionMethodAsync( searchScope, "Deconstruct", type, m => m.ReturnsVoid).ConfigureAwait(false); } } return ImmutableArray<SymbolReference>.Empty; } private async Task<ImmutableArray<SymbolReference>> GetReferencesForExtensionMethodAsync( SearchScope searchScope, string name, ITypeSymbol type, Func<IMethodSymbol, bool> predicate = null) { var symbols = await searchScope.FindDeclarationsAsync( name, nameNode: null, filter: SymbolFilter.Member).ConfigureAwait(false); // Note: there is no "desiredName" when doing this. We're not going to do any // renames of the user code. We're just looking for an extension method called // "Select", but that name has no bearing on the code in question that we're // trying to fix up. var methodSymbols = OfType<IMethodSymbol>(symbols).SelectAsArray(s => s.WithDesiredName(null)); var viableExtensionMethods = GetViableExtensionMethods(methodSymbols, type); if (predicate != null) { viableExtensionMethods = viableExtensionMethods.WhereAsArray(s => predicate(s.Symbol)); } var namespaceSymbols = viableExtensionMethods.SelectAsArray(s => s.WithSymbol(s.Symbol.ContainingNamespace)); return GetNamespaceSymbolReferences(searchScope, namespaceSymbols); } protected bool ExpressionBinds( TSimpleNameSyntax nameNode, bool checkForExtensionMethods, CancellationToken cancellationToken) { // See if the name binds to something other then the error type. If it does, there's nothing further we need to do. // For extension methods, however, we will continue to search if there exists any better matched method. cancellationToken.ThrowIfCancellationRequested(); var symbolInfo = _semanticModel.GetSymbolInfo(nameNode, cancellationToken); if (symbolInfo.CandidateReason == CandidateReason.OverloadResolutionFailure && !checkForExtensionMethods) { return true; } return symbolInfo.Symbol != null; } private ImmutableArray<SymbolReference> GetNamespaceSymbolReferences( SearchScope scope, ImmutableArray<SymbolResult<INamespaceSymbol>> namespaces) { using var _ = ArrayBuilder<SymbolReference>.GetInstance(out var references); foreach (var namespaceResult in namespaces) { var symbol = namespaceResult.Symbol; var mappedResult = namespaceResult.WithSymbol(MapToCompilationNamespaceIfPossible(namespaceResult.Symbol)); var namespaceIsInScope = _namespacesInScope.Contains(mappedResult.Symbol); if (!symbol.IsGlobalNamespace && !namespaceIsInScope) references.Add(scope.CreateReference(mappedResult)); } return references.ToImmutable(); } private static ImmutableArray<SymbolResult<T>> OfType<T>(ImmutableArray<SymbolResult<ISymbol>> symbols) where T : ISymbol { return symbols.WhereAsArray(s => s.Symbol is T) .SelectAsArray(s => s.WithSymbol((T)s.Symbol)); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Packaging; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.SymbolSearch; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.Shared.Utilities.EditorBrowsableHelpers; namespace Microsoft.CodeAnalysis.AddImport { internal abstract partial class AbstractAddImportFeatureService<TSimpleNameSyntax> { private partial class SymbolReferenceFinder { private const string AttributeSuffix = nameof(Attribute); private readonly string _diagnosticId; private readonly Document _document; private readonly SemanticModel _semanticModel; private readonly ISet<INamespaceSymbol> _namespacesInScope; private readonly ISyntaxFactsService _syntaxFacts; private readonly AbstractAddImportFeatureService<TSimpleNameSyntax> _owner; private readonly SyntaxNode _node; private readonly ISymbolSearchService _symbolSearchService; private readonly bool _searchReferenceAssemblies; private readonly ImmutableArray<PackageSource> _packageSources; public SymbolReferenceFinder( AbstractAddImportFeatureService<TSimpleNameSyntax> owner, Document document, SemanticModel semanticModel, string diagnosticId, SyntaxNode node, ISymbolSearchService symbolSearchService, bool searchReferenceAssemblies, ImmutableArray<PackageSource> packageSources, CancellationToken cancellationToken) { _owner = owner; _document = document; _semanticModel = semanticModel; _diagnosticId = diagnosticId; _node = node; _symbolSearchService = symbolSearchService; _searchReferenceAssemblies = searchReferenceAssemblies; _packageSources = packageSources; if (_searchReferenceAssemblies || packageSources.Length > 0) { Contract.ThrowIfNull(symbolSearchService); } _syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); _namespacesInScope = GetNamespacesInScope(cancellationToken); } private ISet<INamespaceSymbol> GetNamespacesInScope(CancellationToken cancellationToken) { // Add all the namespaces brought in by imports/usings. var set = _owner.GetImportNamespacesInScope(_semanticModel, _node, cancellationToken); // Also add all the namespaces we're contained in. We don't want // to add imports for these namespaces either. for (var containingNamespace = _semanticModel.GetEnclosingNamespace(_node.SpanStart, cancellationToken); containingNamespace != null; containingNamespace = containingNamespace.ContainingNamespace) { set.Add(MapToCompilationNamespaceIfPossible(containingNamespace)); } return set; } private INamespaceSymbol MapToCompilationNamespaceIfPossible(INamespaceSymbol containingNamespace) => _semanticModel.Compilation.GetCompilationNamespace(containingNamespace) ?? containingNamespace; internal Task<ImmutableArray<SymbolReference>> FindInAllSymbolsInStartingProjectAsync( bool exact, CancellationToken cancellationToken) { var searchScope = new AllSymbolsProjectSearchScope( _owner, _document.Project, exact, cancellationToken); return DoAsync(searchScope); } internal Task<ImmutableArray<SymbolReference>> FindInSourceSymbolsInProjectAsync( ConcurrentDictionary<Project, AsyncLazy<IAssemblySymbol>> projectToAssembly, Project project, bool exact, CancellationToken cancellationToken) { var searchScope = new SourceSymbolsProjectSearchScope( _owner, projectToAssembly, project, exact, cancellationToken); return DoAsync(searchScope); } internal Task<ImmutableArray<SymbolReference>> FindInMetadataSymbolsAsync( IAssemblySymbol assembly, ProjectId assemblyProjectId, PortableExecutableReference metadataReference, bool exact, CancellationToken cancellationToken) { var searchScope = new MetadataSymbolsSearchScope( _owner, _document.Project.Solution, assembly, assemblyProjectId, metadataReference, exact, cancellationToken); return DoAsync(searchScope); } private async Task<ImmutableArray<SymbolReference>> DoAsync(SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); // Spin off tasks to do all our searching in parallel using var _1 = ArrayBuilder<Task<ImmutableArray<SymbolReference>>>.GetInstance(out var tasks); tasks.Add(GetReferencesForMatchingTypesAsync(searchScope)); tasks.Add(GetReferencesForMatchingNamespacesAsync(searchScope)); tasks.Add(GetReferencesForMatchingFieldsAndPropertiesAsync(searchScope)); tasks.Add(GetReferencesForMatchingExtensionMethodsAsync(searchScope)); // Searching for things like "Add" (for collection initializers) and "Select" // (for extension methods) should only be done when doing an 'exact' search. // We should not do fuzzy searches for these names. In this case it's not // like the user was writing Add or Select, but instead we're looking for // viable symbols with those names to make a collection initializer or // query expression valid. if (searchScope.Exact) { tasks.Add(GetReferencesForCollectionInitializerMethodsAsync(searchScope)); tasks.Add(GetReferencesForQueryPatternsAsync(searchScope)); tasks.Add(GetReferencesForDeconstructAsync(searchScope)); tasks.Add(GetReferencesForGetAwaiterAsync(searchScope)); tasks.Add(GetReferencesForGetEnumeratorAsync(searchScope)); tasks.Add(GetReferencesForGetAsyncEnumeratorAsync(searchScope)); } await Task.WhenAll(tasks).ConfigureAwait(false); searchScope.CancellationToken.ThrowIfCancellationRequested(); using var _2 = ArrayBuilder<SymbolReference>.GetInstance(out var allReferences); foreach (var task in tasks) { var taskResult = await task.ConfigureAwait(false); allReferences.AddRange(taskResult); } return DeDupeAndSortReferences(allReferences.ToImmutable()); } private ImmutableArray<SymbolReference> DeDupeAndSortReferences(ImmutableArray<SymbolReference> allReferences) { return allReferences .Distinct() .Where(NotNull) .Where(NotGlobalNamespace) .OrderBy((r1, r2) => r1.CompareTo(_document, r2)) .ToImmutableArray(); } private static void CalculateContext( TSimpleNameSyntax nameNode, ISyntaxFactsService syntaxFacts, out string name, out int arity, out bool inAttributeContext, out bool hasIncompleteParentMember, out bool looksGeneric) { // Has to be a simple identifier or generic name. syntaxFacts.GetNameAndArityOfSimpleName(nameNode, out name, out arity); inAttributeContext = syntaxFacts.IsAttributeName(nameNode); hasIncompleteParentMember = nameNode?.Parent?.RawKind == syntaxFacts.SyntaxKinds.IncompleteMember; looksGeneric = syntaxFacts.LooksGeneric(nameNode); } /// <summary> /// Searches for types that match the name the user has written. Returns <see cref="SymbolReference"/>s /// to the <see cref="INamespaceSymbol"/>s or <see cref="INamedTypeSymbol"/>s those types are /// contained in. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForMatchingTypesAsync(SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (!_owner.CanAddImportForType(_diagnosticId, _node, out var nameNode)) { return ImmutableArray<SymbolReference>.Empty; } CalculateContext( nameNode, _syntaxFacts, out var name, out var arity, out var inAttributeContext, out var hasIncompleteParentMember, out var looksGeneric); if (ExpressionBinds(nameNode, checkForExtensionMethods: false, cancellationToken: searchScope.CancellationToken)) { // If the expression bound, there's nothing to do. return ImmutableArray<SymbolReference>.Empty; } var symbols = await searchScope.FindDeclarationsAsync(name, nameNode, SymbolFilter.Type).ConfigureAwait(false); // also lookup type symbols with the "Attribute" suffix if necessary. if (inAttributeContext) { var attributeSymbols = await searchScope.FindDeclarationsAsync(name + AttributeSuffix, nameNode, SymbolFilter.Type).ConfigureAwait(false); symbols = symbols.AddRange( attributeSymbols.Select(r => r.WithDesiredName(r.DesiredName.GetWithoutAttributeSuffix(isCaseSensitive: false)))); } var typeSymbols = OfType<ITypeSymbol>(symbols); var options = await _document.GetOptionsAsync(searchScope.CancellationToken).ConfigureAwait(false); var hideAdvancedMembers = options.GetOption(CompletionOptions.HideAdvancedMembers); var editorBrowserInfo = new EditorBrowsableInfo(_semanticModel.Compilation); // Only keep symbols which are accessible from the current location and that are allowed by the current // editor browsable rules. var accessibleTypeSymbols = typeSymbols.WhereAsArray( s => ArityAccessibilityAndAttributeContextAreCorrect(s.Symbol, arity, inAttributeContext, hasIncompleteParentMember, looksGeneric) && s.Symbol.IsEditorBrowsable(hideAdvancedMembers, _semanticModel.Compilation, editorBrowserInfo)); // These types may be contained within namespaces, or they may be nested // inside generic types. Record these namespaces/types if it would be // legal to add imports for them. var typesContainedDirectlyInNamespaces = accessibleTypeSymbols.WhereAsArray(s => s.Symbol.ContainingSymbol is INamespaceSymbol); var typesContainedDirectlyInTypes = accessibleTypeSymbols.WhereAsArray(s => s.Symbol.ContainingType != null); var namespaceReferences = GetNamespaceSymbolReferences(searchScope, typesContainedDirectlyInNamespaces.SelectAsArray(r => r.WithSymbol(r.Symbol.ContainingNamespace))); var typeReferences = typesContainedDirectlyInTypes.SelectAsArray( r => searchScope.CreateReference(r.WithSymbol(r.Symbol.ContainingType))); return namespaceReferences.Concat(typeReferences); } private bool ArityAccessibilityAndAttributeContextAreCorrect( ITypeSymbol symbol, int arity, bool inAttributeContext, bool hasIncompleteParentMember, bool looksGeneric) { if (inAttributeContext && !symbol.IsAttribute()) { return false; } if (!symbol.IsAccessibleWithin(_semanticModel.Compilation.Assembly)) { return false; } if (looksGeneric && symbol.GetTypeArguments().Length == 0) { return false; } return arity == 0 || symbol.GetArity() == arity || hasIncompleteParentMember; } /// <summary> /// Searches for namespaces that match the name the user has written. Returns <see cref="SymbolReference"/>s /// to the <see cref="INamespaceSymbol"/>s those namespaces are contained in. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForMatchingNamespacesAsync( SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (_owner.CanAddImportForNamespace(_diagnosticId, _node, out var nameNode)) { _syntaxFacts.GetNameAndArityOfSimpleName(nameNode, out var name, out var arity); if (arity == 0 && !ExpressionBinds(nameNode, checkForExtensionMethods: false, cancellationToken: searchScope.CancellationToken)) { var symbols = await searchScope.FindDeclarationsAsync(name, nameNode, SymbolFilter.Namespace).ConfigureAwait(false); var namespaceSymbols = OfType<INamespaceSymbol>(symbols); var containingNamespaceSymbols = OfType<INamespaceSymbol>(symbols).SelectAsArray(s => s.WithSymbol(s.Symbol.ContainingNamespace)); return GetNamespaceSymbolReferences(searchScope, containingNamespaceSymbols); } } return ImmutableArray<SymbolReference>.Empty; } /// <summary> /// Specialized finder for the "Color Color" case. Used when we have "Color.Black" and "Color" /// bound to a Field/Property, but not a type. In this case, we want to look for namespaces /// containing 'Color' as if we import them it can resolve this issue. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForMatchingFieldsAndPropertiesAsync( SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (_owner.CanAddImportForMethod(_diagnosticId, _syntaxFacts, _node, out var nameNode) && nameNode != null) { // We have code like "Color.Black". "Color" bound to a 'Color Color' property, and // 'Black' did not bind. We want to find a type called 'Color' that will actually // allow 'Black' to bind. var syntaxFacts = _document.GetLanguageService<ISyntaxFactsService>(); if (syntaxFacts.IsNameOfSimpleMemberAccessExpression(nameNode) || syntaxFacts.IsNameOfMemberBindingExpression(nameNode)) { var expression = syntaxFacts.IsNameOfSimpleMemberAccessExpression(nameNode) ? syntaxFacts.GetExpressionOfMemberAccessExpression(nameNode.Parent, allowImplicitTarget: true) : syntaxFacts.GetTargetOfMemberBinding(nameNode.Parent); if (expression is TSimpleNameSyntax simpleName) { // Check if the expression before the dot binds to a property or field. var symbol = _semanticModel.GetSymbolInfo(expression, searchScope.CancellationToken).GetAnySymbol(); if (symbol?.Kind is SymbolKind.Property or SymbolKind.Field) { // Check if we have the 'Color Color' case. var propertyOrFieldType = symbol.GetSymbolType(); if (propertyOrFieldType is INamedTypeSymbol propertyType && Equals(propertyType.Name, symbol.Name)) { // Try to look up 'Color' as a type. var symbolResults = await searchScope.FindDeclarationsAsync( symbol.Name, simpleName, SymbolFilter.Type).ConfigureAwait(false); // Return results that have accessible members. var namedTypeSymbols = OfType<INamedTypeSymbol>(symbolResults); var name = nameNode.GetFirstToken().ValueText; var namespaceResults = namedTypeSymbols.WhereAsArray(sr => HasAccessibleStaticFieldOrProperty(sr.Symbol, name)) .SelectAsArray(sr => sr.WithSymbol(sr.Symbol.ContainingNamespace)); return GetNamespaceSymbolReferences(searchScope, namespaceResults); } } } } } return ImmutableArray<SymbolReference>.Empty; } private bool HasAccessibleStaticFieldOrProperty(INamedTypeSymbol namedType, string fieldOrPropertyName) { return namedType.GetMembers(fieldOrPropertyName) .Any(m => (m is IFieldSymbol || m is IPropertySymbol) && m.IsStatic && m.IsAccessibleWithin(_semanticModel.Compilation.Assembly)); } /// <summary> /// Searches for extension methods that match the name the user has written. Returns /// <see cref="SymbolReference"/>s to the <see cref="INamespaceSymbol"/>s that contain /// the static classes that those extension methods are contained in. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForMatchingExtensionMethodsAsync(SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (_owner.CanAddImportForMethod(_diagnosticId, _syntaxFacts, _node, out var nameNode) && nameNode != null) { searchScope.CancellationToken.ThrowIfCancellationRequested(); // See if the name binds. If it does, there's nothing further we need to do. if (!ExpressionBinds(nameNode, checkForExtensionMethods: true, cancellationToken: searchScope.CancellationToken)) { _syntaxFacts.GetNameAndArityOfSimpleName(nameNode, out var name, out var arity); if (name != null) { var symbols = await searchScope.FindDeclarationsAsync(name, nameNode, SymbolFilter.Member).ConfigureAwait(false); var methodSymbols = OfType<IMethodSymbol>(symbols); var extensionMethodSymbols = GetViableExtensionMethods( methodSymbols, nameNode.Parent, searchScope.CancellationToken); var namespaceSymbols = extensionMethodSymbols.SelectAsArray(s => s.WithSymbol(s.Symbol.ContainingNamespace)); return GetNamespaceSymbolReferences(searchScope, namespaceSymbols); } } } return ImmutableArray<SymbolReference>.Empty; } private ImmutableArray<SymbolResult<IMethodSymbol>> GetViableExtensionMethods( ImmutableArray<SymbolResult<IMethodSymbol>> methodSymbols, SyntaxNode expression, CancellationToken cancellationToken) { return GetViableExtensionMethodsWorker(methodSymbols).WhereAsArray( s => _owner.IsViableExtensionMethod(s.Symbol, expression, _semanticModel, _syntaxFacts, cancellationToken)); } private ImmutableArray<SymbolResult<IMethodSymbol>> GetViableExtensionMethods( ImmutableArray<SymbolResult<IMethodSymbol>> methodSymbols, ITypeSymbol typeSymbol) { return GetViableExtensionMethodsWorker(methodSymbols).WhereAsArray( s => IsViableExtensionMethod(s.Symbol, typeSymbol)); } private ImmutableArray<SymbolResult<IMethodSymbol>> GetViableExtensionMethodsWorker( ImmutableArray<SymbolResult<IMethodSymbol>> methodSymbols) { return methodSymbols.WhereAsArray( s => s.Symbol.IsExtensionMethod && s.Symbol.IsAccessibleWithin(_semanticModel.Compilation.Assembly)); } /// <summary> /// Searches for extension methods exactly called 'Add'. Returns /// <see cref="SymbolReference"/>s to the <see cref="INamespaceSymbol"/>s that contain /// the static classes that those extension methods are contained in. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForCollectionInitializerMethodsAsync(SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (_owner.CanAddImportForMethod(_diagnosticId, _syntaxFacts, _node, out _) && !_syntaxFacts.IsSimpleName(_node) && _owner.IsAddMethodContext(_node, _semanticModel)) { var symbols = await searchScope.FindDeclarationsAsync( nameof(IList.Add), nameNode: null, filter: SymbolFilter.Member).ConfigureAwait(false); // Note: there is no desiredName for these search results. We're searching for // extension methods called "Add", but we have no intention of renaming any // of the existing user code to that name. var methodSymbols = OfType<IMethodSymbol>(symbols).SelectAsArray(s => s.WithDesiredName(null)); var viableMethods = GetViableExtensionMethods( methodSymbols, _node.Parent, searchScope.CancellationToken); return GetNamespaceSymbolReferences(searchScope, viableMethods.SelectAsArray(m => m.WithSymbol(m.Symbol.ContainingNamespace))); } return ImmutableArray<SymbolReference>.Empty; } /// <summary> /// Searches for extension methods exactly called 'Select'. Returns /// <see cref="SymbolReference"/>s to the <see cref="INamespaceSymbol"/>s that contain /// the static classes that those extension methods are contained in. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForQueryPatternsAsync(SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (_owner.CanAddImportForQuery(_diagnosticId, _node)) { var type = _owner.GetQueryClauseInfo(_semanticModel, _node, searchScope.CancellationToken); if (type != null) { // find extension methods named "Select" return await GetReferencesForExtensionMethodAsync( searchScope, nameof(Enumerable.Select), type).ConfigureAwait(false); } } return ImmutableArray<SymbolReference>.Empty; } /// <summary> /// Searches for extension methods exactly called 'GetAwaiter'. Returns /// <see cref="SymbolReference"/>s to the <see cref="INamespaceSymbol"/>s that contain /// the static classes that those extension methods are contained in. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForGetAwaiterAsync(SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (_owner.CanAddImportForGetAwaiter(_diagnosticId, _syntaxFacts, _node)) { var type = GetAwaitInfo(_semanticModel, _syntaxFacts, _node); if (type != null) { return await GetReferencesForExtensionMethodAsync(searchScope, WellKnownMemberNames.GetAwaiter, type, m => m.IsValidGetAwaiter()).ConfigureAwait(false); } } return ImmutableArray<SymbolReference>.Empty; } /// <summary> /// Searches for extension methods exactly called 'GetEnumerator'. Returns /// <see cref="SymbolReference"/>s to the <see cref="INamespaceSymbol"/>s that contain /// the static classes that those extension methods are contained in. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForGetEnumeratorAsync(SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (_owner.CanAddImportForGetEnumerator(_diagnosticId, _syntaxFacts, _node)) { var type = GetCollectionExpressionType(_semanticModel, _syntaxFacts, _node); if (type != null) { return await GetReferencesForExtensionMethodAsync(searchScope, WellKnownMemberNames.GetEnumeratorMethodName, type, m => m.IsValidGetEnumerator()).ConfigureAwait(false); } } return ImmutableArray<SymbolReference>.Empty; } /// <summary> /// Searches for extension methods exactly called 'GetAsyncEnumerator'. Returns /// <see cref="SymbolReference"/>s to the <see cref="INamespaceSymbol"/>s that contain /// the static classes that those extension methods are contained in. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForGetAsyncEnumeratorAsync(SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (_owner.CanAddImportForGetAsyncEnumerator(_diagnosticId, _syntaxFacts, _node)) { var type = GetCollectionExpressionType(_semanticModel, _syntaxFacts, _node); if (type != null) { return await GetReferencesForExtensionMethodAsync(searchScope, WellKnownMemberNames.GetAsyncEnumeratorMethodName, type, m => m.IsValidGetAsyncEnumerator()).ConfigureAwait(false); } } return ImmutableArray<SymbolReference>.Empty; } /// <summary> /// Searches for extension methods exactly called 'Deconstruct'. Returns /// <see cref="SymbolReference"/>s to the <see cref="INamespaceSymbol"/>s that contain /// the static classes that those extension methods are contained in. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForDeconstructAsync(SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (_owner.CanAddImportForDeconstruct(_diagnosticId, _node)) { var type = _owner.GetDeconstructInfo(_semanticModel, _node, searchScope.CancellationToken); if (type != null) { // Note: we could check that the extension methods have the right number of out-params. // But that would involve figuring out what we're trying to deconstruct into. For now // we'll just be permissive, with the assumption that there won't be that many matching // 'Deconstruct' extension methods for the type of node that we're on. return await GetReferencesForExtensionMethodAsync( searchScope, "Deconstruct", type, m => m.ReturnsVoid).ConfigureAwait(false); } } return ImmutableArray<SymbolReference>.Empty; } private async Task<ImmutableArray<SymbolReference>> GetReferencesForExtensionMethodAsync( SearchScope searchScope, string name, ITypeSymbol type, Func<IMethodSymbol, bool> predicate = null) { var symbols = await searchScope.FindDeclarationsAsync( name, nameNode: null, filter: SymbolFilter.Member).ConfigureAwait(false); // Note: there is no "desiredName" when doing this. We're not going to do any // renames of the user code. We're just looking for an extension method called // "Select", but that name has no bearing on the code in question that we're // trying to fix up. var methodSymbols = OfType<IMethodSymbol>(symbols).SelectAsArray(s => s.WithDesiredName(null)); var viableExtensionMethods = GetViableExtensionMethods(methodSymbols, type); if (predicate != null) { viableExtensionMethods = viableExtensionMethods.WhereAsArray(s => predicate(s.Symbol)); } var namespaceSymbols = viableExtensionMethods.SelectAsArray(s => s.WithSymbol(s.Symbol.ContainingNamespace)); return GetNamespaceSymbolReferences(searchScope, namespaceSymbols); } protected bool ExpressionBinds( TSimpleNameSyntax nameNode, bool checkForExtensionMethods, CancellationToken cancellationToken) { // See if the name binds to something other then the error type. If it does, there's nothing further we need to do. // For extension methods, however, we will continue to search if there exists any better matched method. cancellationToken.ThrowIfCancellationRequested(); var symbolInfo = _semanticModel.GetSymbolInfo(nameNode, cancellationToken); if (symbolInfo.CandidateReason == CandidateReason.OverloadResolutionFailure && !checkForExtensionMethods) { return true; } return symbolInfo.Symbol != null; } private ImmutableArray<SymbolReference> GetNamespaceSymbolReferences( SearchScope scope, ImmutableArray<SymbolResult<INamespaceSymbol>> namespaces) { using var _ = ArrayBuilder<SymbolReference>.GetInstance(out var references); foreach (var namespaceResult in namespaces) { var symbol = namespaceResult.Symbol; var mappedResult = namespaceResult.WithSymbol(MapToCompilationNamespaceIfPossible(namespaceResult.Symbol)); var namespaceIsInScope = _namespacesInScope.Contains(mappedResult.Symbol); if (!symbol.IsGlobalNamespace && !namespaceIsInScope) references.Add(scope.CreateReference(mappedResult)); } return references.ToImmutable(); } private static ImmutableArray<SymbolResult<T>> OfType<T>(ImmutableArray<SymbolResult<ISymbol>> symbols) where T : ISymbol { return symbols.WhereAsArray(s => s.Symbol is T) .SelectAsArray(s => s.WithSymbol((T)s.Symbol)); } } } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/Compilers/CSharp/Test/Semantic/Semantics/PatternMatchingTests2.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { [CompilerTrait(CompilerFeature.Patterns)] public class PatternMatchingTests2 : PatternMatchingTestBase { [Fact] public void Patterns2_00() { var source = @" using System; class Program { public static void Main() { Console.WriteLine(1 is int {} x ? x : -1); } } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: @"1"); } [Fact] public void Patterns2_01() { var source = @" using System; class Program { public static void Main() { Point p = new Point(); Check(true, p is Point(3, 4) { Length: 5 } q1 && Check(p, q1)); Check(false, p is Point(1, 4) { Length: 5 }); Check(false, p is Point(3, 1) { Length: 5 }); Check(false, p is Point(3, 4) { Length: 1 }); Check(true, p is (3, 4) { Length: 5 } q2 && Check(p, q2)); Check(false, p is (1, 4) { Length: 5 }); Check(false, p is (3, 1) { Length: 5 }); Check(false, p is (3, 4) { Length: 1 }); } private static bool Check<T>(T expected, T actual) { if (!object.Equals(expected, actual)) throw new Exception($""expected: {expected}; actual: {actual}""); return true; } } public class Point { public void Deconstruct(out int X, out int Y) { X = 3; Y = 4; } public int Length => 5; } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: ""); } [Fact] public void Patterns2_02() { var source = @" using System; class Program { public static void Main() { Point p = new Point(); Check(true, p is Point(3, 4) { Length: 5 } q1 && Check(p, q1)); Check(false, p is Point(1, 4) { Length: 5 }); Check(false, p is Point(3, 1) { Length: 5 }); Check(false, p is Point(3, 4) { Length: 1 }); Check(true, p is (3, 4) { Length: 5 } q2 && Check(p, q2)); Check(false, p is (1, 4) { Length: 5 }); Check(false, p is (3, 1) { Length: 5 }); Check(false, p is (3, 4) { Length: 1 }); } private static bool Check<T>(T expected, T actual) { if (!object.Equals(expected, actual)) throw new Exception($""expected: {expected}; actual: {actual}""); return true; } } public class Point { public int Length => 5; } public static class PointExtensions { public static void Deconstruct(this Point p, out int X, out int Y) { X = 3; Y = 4; } } "; // We use a compilation profile that provides System.Runtime.CompilerServices.ExtensionAttribute needed for this test var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularWithRecursivePatterns); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: ""); } [Fact] public void Patterns2_03() { var source = @" using System; class Program { public static void Main() { var p = (x: 3, y: 4); Check(true, p is (3, 4) q1 && Check(p, q1)); Check(false, p is (1, 4) { x: 3 }); Check(false, p is (3, 1) { y: 4 }); Check(false, p is (3, 4) { x: 1 }); Check(true, p is (3, 4) { x: 3 } q2 && Check(p, q2)); Check(false, p is (1, 4) { x: 3 }); Check(false, p is (3, 1) { x: 3 }); Check(false, p is (3, 4) { x: 1 }); } private static bool Check<T>(T expected, T actual) { if (!object.Equals(expected, actual)) throw new Exception($""expected: {expected}; actual: {actual}""); return true; } }"; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (9,22): error CS8415: An expression of type '(int x, int y)' can never match the provided pattern. // Check(false, p is (1, 4) { x: 3 }); Diagnostic(ErrorCode.ERR_IsPatternImpossible, "p is (1, 4) { x: 3 }").WithArguments("(int x, int y)").WithLocation(9, 22), // (10,22): error CS8415: An expression of type '(int x, int y)' can never match the provided pattern. // Check(false, p is (3, 1) { y: 4 }); Diagnostic(ErrorCode.ERR_IsPatternImpossible, "p is (3, 1) { y: 4 }").WithArguments("(int x, int y)").WithLocation(10, 22), // (11,22): error CS8415: An expression of type '(int x, int y)' can never match the provided pattern. // Check(false, p is (3, 4) { x: 1 }); Diagnostic(ErrorCode.ERR_IsPatternImpossible, "p is (3, 4) { x: 1 }").WithArguments("(int x, int y)").WithLocation(11, 22), // (13,22): error CS8415: An expression of type '(int x, int y)' can never match the provided pattern. // Check(false, p is (1, 4) { x: 3 }); Diagnostic(ErrorCode.ERR_IsPatternImpossible, "p is (1, 4) { x: 3 }").WithArguments("(int x, int y)").WithLocation(13, 22), // (15,22): error CS8415: An expression of type '(int x, int y)' can never match the provided pattern. // Check(false, p is (3, 4) { x: 1 }); Diagnostic(ErrorCode.ERR_IsPatternImpossible, "p is (3, 4) { x: 1 }").WithArguments("(int x, int y)").WithLocation(15, 22) ); } [Fact] public void Patterns2_04b() { var source = @" using System; class Program { public static void Main() { var p = (x: 3, y: 4); Check(true, p is (3, 4) q1 && Check(p, q1)); Check(true, p is (3, 4) { x: 3 } q2 && Check(p, q2)); Check(false, p is (3, 1) { x: 3 }); } private static bool Check<T>(T expected, T actual) { if (!object.Equals(expected, actual)) throw new Exception($""expected: {expected}; actual: {actual}""); return true; } }"; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: ""); } [Fact] public void Patterns2_DiscardPattern_01() { var source = @" using System; class Program { public static void Main() { Point p = new Point(); Check(true, p is Point(_, _) { Length: _ } q1 && Check(p, q1)); Check(false, p is Point(1, _) { Length: _ }); Check(false, p is Point(_, 1) { Length: _ }); Check(false, p is Point(_, _) { Length: 1 }); Check(true, p is (_, _) { Length: _ } q2 && Check(p, q2)); Check(false, p is (1, _) { Length: _ }); Check(false, p is (_, 1) { Length: _ }); Check(false, p is (_, _) { Length: 1 }); } private static bool Check<T>(T expected, T actual) { if (!object.Equals(expected, actual)) throw new Exception($""expected: {expected}; actual: {actual}""); return true; } } public class Point { public void Deconstruct(out int X, out int Y) { X = 3; Y = 4; } public int Length => 5; } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: ""); } [Fact] public void Patterns2_Switch01() { var sourceTemplate = @" class Program {{ public static void Main() {{ var p = (true, false); switch (p) {{ {0} {1} {2} case (_, _): // error - subsumed break; }} }} }}"; void testErrorCase(string s1, string s2, string s3) { var source = string.Format(sourceTemplate, s1, s2, s3); var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (12,18): error CS8120: The switch case is unreachable. It has already been handled by a previous case or it is impossible to match. // case (_, _): // error - subsumed Diagnostic(ErrorCode.ERR_SwitchCaseSubsumed, "(_, _)").WithLocation(12, 18) ); } void testGoodCase(string s1, string s2) { var source = string.Format(sourceTemplate, s1, s2, string.Empty); var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( ); } var c1 = "case (true, _):"; var c2 = "case (false, false):"; var c3 = "case (_, true):"; testErrorCase(c1, c2, c3); testErrorCase(c2, c3, c1); testErrorCase(c3, c1, c2); testErrorCase(c1, c3, c2); testErrorCase(c3, c2, c1); testErrorCase(c2, c1, c3); testGoodCase(c1, c2); testGoodCase(c1, c3); testGoodCase(c2, c3); testGoodCase(c2, c1); testGoodCase(c3, c1); testGoodCase(c3, c2); } [Fact] public void Patterns2_Switch02() { var source = @" class Program { public static void Main() { Point p = new Point(); switch (p) { case Point(3, 4) { Length: 5 }: System.Console.WriteLine(true); break; default: System.Console.WriteLine(false); break; } } } public class Point { public void Deconstruct(out int X, out int Y) { X = 3; Y = 4; } public int Length => 5; } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: "True"); } [Fact] public void DefaultPattern() { var source = @"class Program { public static void Main() { int i = 12; if (i is default) {} // error 1 if (i is (default)) {} // error 2 switch (i) { case default: break; } // error 3 switch (i) { case default when true: break; } // error 4 switch ((1, 2)) { case (1, default): break; } // error 5 if (i is < default) {} // error 6 switch (i) { case < default: break; } // error 7 if (i is < ((default))) {} // error 8 switch (i) { case < ((default)): break; } // error 9 if (i is default!) {} // error 10 if (i is (default!)) {} // error 11 if (i is < ((default)!)) {} // error 12 if (i is default!!) {} // error 13 if (i is (default!!)) {} // error 14 if (i is < ((default)!!)) {} // error 15 // These are not accepted by the parser. See https://github.com/dotnet/roslyn/issues/45387 if (i is (default)!) {} // error 16 if (i is ((default)!)) {} // error 17 } }"; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (6,18): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'. // if (i is default) {} // error 1 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(6, 18), // (7,19): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'. // if (i is (default)) {} // error 2 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(7, 19), // (8,27): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'. // switch (i) { case default: break; } // error 3 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(8, 27), // (9,27): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'. // switch (i) { case default when true: break; } // error 4 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(9, 27), // (10,36): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'. // switch ((1, 2)) { case (1, default): break; } // error 5 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(10, 36), // (12,20): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'. // if (i is < default) {} // error 6 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(12, 20), // (13,29): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'. // switch (i) { case < default: break; } // error 7 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(13, 29), // (14,22): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'. // if (i is < ((default))) {} // error 8 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(14, 22), // (15,31): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'. // switch (i) { case < ((default)): break; } // error 9 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(15, 31), // (17,18): error CS8598: The suppression operator is not allowed in this context // if (i is default!) {} // error 10 Diagnostic(ErrorCode.ERR_IllegalSuppression, "default!").WithLocation(17, 18), // (17,18): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'. // if (i is default!) {} // error 10 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(17, 18), // (18,19): error CS8598: The suppression operator is not allowed in this context // if (i is (default!)) {} // error 11 Diagnostic(ErrorCode.ERR_IllegalSuppression, "default!").WithLocation(18, 19), // (18,19): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'. // if (i is (default!)) {} // error 11 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(18, 19), // (19,21): error CS8598: The suppression operator is not allowed in this context // if (i is < ((default)!)) {} // error 12 Diagnostic(ErrorCode.ERR_IllegalSuppression, "(default)!").WithLocation(19, 21), // (19,22): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'. // if (i is < ((default)!)) {} // error 12 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(19, 22), // (20,18): error CS8598: The suppression operator is not allowed in this context // if (i is default!!) {} // error 13 Diagnostic(ErrorCode.ERR_IllegalSuppression, "default!!").WithLocation(20, 18), // (20,18): error CS8598: The suppression operator is not allowed in this context // if (i is default!!) {} // error 13 Diagnostic(ErrorCode.ERR_IllegalSuppression, "default!").WithLocation(20, 18), // (20,18): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'. // if (i is default!!) {} // error 13 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(20, 18), // (21,19): error CS8598: The suppression operator is not allowed in this context // if (i is (default!!)) {} // error 14 Diagnostic(ErrorCode.ERR_IllegalSuppression, "default!!").WithLocation(21, 19), // (21,19): error CS8598: The suppression operator is not allowed in this context // if (i is (default!!)) {} // error 14 Diagnostic(ErrorCode.ERR_IllegalSuppression, "default!").WithLocation(21, 19), // (21,19): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'. // if (i is (default!!)) {} // error 14 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(21, 19), // (22,21): error CS8598: The suppression operator is not allowed in this context // if (i is < ((default)!!)) {} // error 15 Diagnostic(ErrorCode.ERR_IllegalSuppression, "(default)!!").WithLocation(22, 21), // (22,21): error CS8598: The suppression operator is not allowed in this context // if (i is < ((default)!!)) {} // error 15 Diagnostic(ErrorCode.ERR_IllegalSuppression, "(default)!").WithLocation(22, 21), // (22,22): error CS8715: Duplicate null suppression operator ('!') // if (i is < ((default)!!)) {} // error 15 Diagnostic(ErrorCode.ERR_DuplicateNullSuppression, "default").WithLocation(22, 22), // (22,22): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'. // if (i is < ((default)!!)) {} // error 15 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(22, 22), // (25,19): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'. // if (i is (default)!) {} // error 16 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(25, 19), // (25,27): error CS1026: ) expected // if (i is (default)!) {} // error 16 Diagnostic(ErrorCode.ERR_CloseParenExpected, "!").WithLocation(25, 27), // (25,28): error CS1525: Invalid expression term ')' // if (i is (default)!) {} // error 16 Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(25, 28), // (25,28): error CS1002: ; expected // if (i is (default)!) {} // error 16 Diagnostic(ErrorCode.ERR_SemicolonExpected, ")").WithLocation(25, 28), // (25,28): error CS1513: } expected // if (i is (default)!) {} // error 16 Diagnostic(ErrorCode.ERR_RbraceExpected, ")").WithLocation(25, 28), // (26,18): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'int', with 2 out parameters and a void return type. // if (i is ((default)!)) {} // error 17 Diagnostic(ErrorCode.ERR_MissingDeconstruct, "((default)!)").WithArguments("int", "2").WithLocation(26, 18), // (26,20): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'. // if (i is ((default)!)) {} // error 17 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(26, 20), // (26,28): error CS1003: Syntax error, ',' expected // if (i is ((default)!)) {} // error 17 Diagnostic(ErrorCode.ERR_SyntaxError, "!").WithArguments(",", "!").WithLocation(26, 28), // (26,29): error CS1525: Invalid expression term ')' // if (i is ((default)!)) {} // error 17 Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(26, 29) ); } [Fact] public void SwitchExpression_01() { // test appropriate language version or feature flag var source = @"class Program { public static void Main() { var r = 1 switch { _ => 0, }; } }"; CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularWithoutRecursivePatterns).VerifyDiagnostics( // (5,17): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // var r = 1 switch { _ => 0, }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "1 switch { _ => 0, }").WithArguments("recursive patterns", "8.0").WithLocation(5, 17) ); CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular8).VerifyDiagnostics(); } [Fact] public void SwitchExpression_02() { // test switch expression's governing expression has no type // test switch expression's governing expression has type void var source = @"class Program { public static void Main() { var r1 = (1, null) switch { _ => 0 }; var r2 = System.Console.Write(1) switch { _ => 0 }; } }"; CreatePatternCompilation(source).VerifyDiagnostics( // (5,18): error CS8117: Invalid operand for pattern match; value required, but found '(int, <null>)'. // var r1 = (1, null) switch ( _ => 0 ); Diagnostic(ErrorCode.ERR_BadPatternExpression, "(1, null)").WithArguments("(int, <null>)").WithLocation(5, 18), // (6,18): error CS8117: Invalid operand for pattern match; value required, but found 'void'. // var r2 = System.Console.Write(1) switch ( _ => 0 ); Diagnostic(ErrorCode.ERR_BadPatternExpression, "System.Console.Write(1)").WithArguments("void").WithLocation(6, 18) ); } [Fact] public void SwitchExpression_03() { // test that a ternary expression is not at an appropriate precedence // for the constant expression of a constant pattern in a switch expression arm. var source = @"class Program { public static void Main() { bool b = true; var r1 = b switch { true ? true : true => true, false => false }; var r2 = b switch { (true ? true : true) => true, false => false }; } }"; // This is admittedly poor syntax error recovery (for the line declaring r2), // but this test demonstrates that it is a syntax error. CreatePatternCompilation(source).VerifyDiagnostics( // (6,34): error CS1003: Syntax error, '=>' expected // var r1 = b switch { true ? true : true => true, false => false }; Diagnostic(ErrorCode.ERR_SyntaxError, "?").WithArguments("=>", "?").WithLocation(6, 34), // (6,34): error CS1525: Invalid expression term '?' // var r1 = b switch { true ? true : true => true, false => false }; Diagnostic(ErrorCode.ERR_InvalidExprTerm, "?").WithArguments("?").WithLocation(6, 34), // (6,48): error CS1003: Syntax error, ',' expected // var r1 = b switch { true ? true : true => true, false => false }; Diagnostic(ErrorCode.ERR_SyntaxError, "=>").WithArguments(",", "=>").WithLocation(6, 48), // (6,48): error CS8504: Pattern missing // var r1 = b switch { true ? true : true => true, false => false }; Diagnostic(ErrorCode.ERR_MissingPattern, "=>").WithLocation(6, 48) ); } [Fact] public void SwitchExpression_04() { // test that a ternary expression is permitted as a constant pattern in recursive contexts and the case expression. var source = @"class Program { public static void Main() { var b = (true, false); var r1 = b switch { (true ? true : true, _) => true, _ => false, }; var r2 = b is (true ? true : true, _); switch (b.Item1) { case true ? true : true: break; } } }"; CreatePatternCompilation(source).VerifyDiagnostics( ); } [Fact] public void SwitchExpression_05() { // test throw expression in match arm. var source = @"class Program { public static void Main() { var x = 1 switch { 1 => 1, _ => throw null }; } }"; CreatePatternCompilation(source).VerifyDiagnostics( ); } [Fact] public void EmptySwitchExpression() { var source = @"class Program { public static void Main() { var r = 1 switch { }; } }"; CreatePatternCompilation(source).VerifyDiagnostics( // (5,19): warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '_' is not covered. // var r = 1 switch { }; Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustive, "switch").WithArguments("_").WithLocation(5, 19), // (5,19): error CS8506: No best type was found for the switch expression. // var r = 1 switch { }; Diagnostic(ErrorCode.ERR_SwitchExpressionNoBestType, "switch").WithLocation(5, 19)); } [Fact] public void SwitchExpression_06() { // test common type vs delegate in match expression var source = @"class Program { public static void Main() { var x = 1 switch { 0 => M, 1 => new D(M), 2 => M }; x(); } public static void M() {} public delegate void D(); }"; CreatePatternCompilation(source).VerifyDiagnostics( // (5,19): warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '3' is not covered. // var x = 1 switch { 0 => M, 1 => new D(M), 2 => M }; Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustive, "switch").WithArguments("3").WithLocation(5, 19) ); } [Fact] public void SwitchExpression_07() { // test flow analysis of the switch expression var source = @"class Program { public static void Main() { int q = 1; int u; var x = q switch { 0 => u=0, 1 => u=1, _ => u=2 }; System.Console.WriteLine(u); } }"; CreatePatternCompilation(source).VerifyDiagnostics( ); } [Fact] public void SwitchExpression_08() { // test flow analysis of the switch expression var source = @"class Program { public static void Main() { int q = 1; int u; var x = q switch { 0 => u=0, 1 => 1, _ => u=2 }; System.Console.WriteLine(u); } static int M(int i) => i; }"; CreatePatternCompilation(source).VerifyDiagnostics( // (8,34): error CS0165: Use of unassigned local variable 'u' // System.Console.WriteLine(u); Diagnostic(ErrorCode.ERR_UseDefViolation, "u").WithArguments("u").WithLocation(8, 34) ); } [Fact] public void SwitchExpression_09() { // test flow analysis of the switch expression var source = @"class Program { public static void Main() { int q = 1; int u; var x = q switch { 0 => u=0, 1 => u=M(u), _ => u=2, }; System.Console.WriteLine(u); } static int M(int i) => i; }"; CreatePatternCompilation(source).VerifyDiagnostics( // (7,47): error CS0165: Use of unassigned local variable 'u' // var x = q switch { 0 => u=0, 1 => u=M(u), _ => u=2 }; Diagnostic(ErrorCode.ERR_UseDefViolation, "u").WithArguments("u").WithLocation(7, 47) ); } [Fact] public void SwitchExpression_10() { // test lazily inferring variables in the pattern // test lazily inferring variables in the when clause // test lazily inferring variables in the arrow expression var source = @"class Program { public static void Main() { int a = 1; var b = a switch { var x1 => x1, }; var c = a switch { var x2 when x2 is var x3 => x3 }; var d = a switch { var x4 => x4 is var x5 ? x5 : 1, }; } static int M(int i) => i; }"; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (7,19): warning CS8846: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '_' is not covered. However, a pattern with a 'when' clause might successfully match this value. // var c = a switch { var x2 when x2 is var x3 => x3 }; Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustiveWithWhen, "switch").WithArguments("_").WithLocation(7, 19) ); var names = new[] { "x1", "x2", "x3", "x4", "x5" }; var tree = compilation.SyntaxTrees[0]; foreach (var designation in tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>()) { var model = compilation.GetSemanticModel(tree); var symbol = model.GetDeclaredSymbol(designation); Assert.Equal(SymbolKind.Local, symbol.Kind); Assert.Equal("int", ((ILocalSymbol)symbol).Type.ToDisplayString()); } foreach (var ident in tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>()) { var model = compilation.GetSemanticModel(tree); var typeInfo = model.GetTypeInfo(ident); Assert.Equal("int", typeInfo.Type.ToDisplayString()); } } [Fact] public void ShortDiscardInIsPattern() { // test that we forbid a short discard at the top level of an is-pattern expression var source = @"class Program { public static void Main() { int a = 1; if (a is _) { } } }"; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (6,18): error CS0246: The type or namespace name '_' could not be found (are you missing a using directive or an assembly reference?) // if (a is _) { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "_").WithArguments("_").WithLocation(6, 18) ); } [Fact] public void Patterns2_04() { // Test that a single-element deconstruct pattern is an error if no further elements disambiguate. var source = @" using System; class Program { public static void Main() { var t = new System.ValueTuple<int>(1); if (t is (int x)) { } // error 1 switch (t) { case (_): break; } // error 2 var u = t switch { (int y) => y, _ => 2 }; // error 3 if (t is (int z1) _) { } // ok if (t is (Item1: int z2)) { } // ok if (t is (int z3) { }) { } // ok if (t is ValueTuple<int>(int z4)) { } // ok } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular8); compilation.VerifyDiagnostics( // (8,18): error CS8400: Feature 'parenthesized pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // if (t is (int x)) { } // error 1 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "(int x)").WithArguments("parenthesized pattern", "9.0").WithLocation(8, 18), // (8,19): error CS8121: An expression of type 'ValueTuple<int>' cannot be handled by a pattern of type 'int'. // if (t is (int x)) { } // error 1 Diagnostic(ErrorCode.ERR_PatternWrongType, "int").WithArguments("System.ValueTuple<int>", "int").WithLocation(8, 19), // (9,27): error CS8400: Feature 'parenthesized pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // switch (t) { case (_): break; } // error 2 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "(_)").WithArguments("parenthesized pattern", "9.0").WithLocation(9, 27), // (10,28): error CS8400: Feature 'parenthesized pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // var u = t switch { (int y) => y, _ => 2 }; // error 3 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "(int y)").WithArguments("parenthesized pattern", "9.0").WithLocation(10, 28), // (10,29): error CS8121: An expression of type 'ValueTuple<int>' cannot be handled by a pattern of type 'int'. // var u = t switch { (int y) => y, _ => 2 }; // error 3 Diagnostic(ErrorCode.ERR_PatternWrongType, "int").WithArguments("System.ValueTuple<int>", "int").WithLocation(10, 29) ); } [Fact] public void Patterns2_05() { // Test parsing the var pattern // Test binding the var pattern // Test lowering the var pattern for the is-expression var source = @" using System; class Program { public static void Main() { var t = (1, 2); { Check(true, t is var (x, y) && x == 1 && y == 2); } { Check(false, t is var (x, y) && x == 1 && y == 3); } } private static void Check<T>(T expected, T actual) { if (!object.Equals(expected, actual)) throw new Exception($""Expected: '{expected}', Actual: '{actual}'""); } }"; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: @""); } [Fact] public void Patterns2_06() { // Test that 'var' does not bind to a type var source = @" using System; namespace N { class Program { public static void Main() { var t = (1, 2); { Check(true, t is var (x, y) && x == 1 && y == 2); } // error 1 { Check(false, t is var (x, y) && x == 1 && y == 3); } // error 2 { Check(true, t is var x); } // error 3 } private static void Check<T>(T expected, T actual) { if (!object.Equals(expected, actual)) throw new Exception($""Expected: '{expected}', Actual: '{actual}'""); } } class var { } }"; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (9,21): error CS0029: Cannot implicitly convert type '(int, int)' to 'N.var' // var t = (1, 2); Diagnostic(ErrorCode.ERR_NoImplicitConv, "(1, 2)").WithArguments("(int, int)", "N.var").WithLocation(9, 21), // (10,32): error CS8508: The syntax 'var' for a pattern is not permitted to refer to a type, but 'N.var' is in scope here. // { Check(true, t is var (x, y) && x == 1 && y == 2); } // error 1 Diagnostic(ErrorCode.ERR_VarMayNotBindToType, "var").WithArguments("N.var").WithLocation(10, 32), // (10,36): error CS1061: 'var' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'var' could be found (are you missing a using directive or an assembly reference?) // { Check(true, t is var (x, y) && x == 1 && y == 2); } // error 1 Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "(x, y)").WithArguments("N.var", "Deconstruct").WithLocation(10, 36), // (10,36): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'var', with 2 out parameters and a void return type. // { Check(true, t is var (x, y) && x == 1 && y == 2); } // error 1 Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(x, y)").WithArguments("N.var", "2").WithLocation(10, 36), // (11,33): error CS8508: The syntax 'var' for a pattern is not permitted to refer to a type, but 'N.var' is in scope here. // { Check(false, t is var (x, y) && x == 1 && y == 3); } // error 2 Diagnostic(ErrorCode.ERR_VarMayNotBindToType, "var").WithArguments("N.var").WithLocation(11, 33), // (11,37): error CS1061: 'var' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'var' could be found (are you missing a using directive or an assembly reference?) // { Check(false, t is var (x, y) && x == 1 && y == 3); } // error 2 Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "(x, y)").WithArguments("N.var", "Deconstruct").WithLocation(11, 37), // (11,37): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'var', with 2 out parameters and a void return type. // { Check(false, t is var (x, y) && x == 1 && y == 3); } // error 2 Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(x, y)").WithArguments("N.var", "2").WithLocation(11, 37), // (12,32): error CS8508: The syntax 'var' for a pattern is not permitted to refer to a type, but 'N.var' is in scope here. // { Check(true, t is var x); } // error 3 Diagnostic(ErrorCode.ERR_VarMayNotBindToType, "var").WithArguments("N.var").WithLocation(12, 32) ); } [Fact] public void Patterns2_10() { var source = @" using System; class Program { public static void Main() { Console.Write(M((false, false))); Console.Write(M((false, true))); Console.Write(M((true, false))); Console.Write(M((true, true))); } private static int M((bool, bool) t) { switch (t) { case (false, false): return 0; case (false, _): return 1; case (_, false): return 2; case var _: return 3; } } } namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } } }"; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: @"0123"); } [Fact] public void Patterns2_11() { var source = @" using System; class Program { public static void Main() { Console.Write(M((false, false))); Console.Write(M((false, true))); Console.Write(M((true, false))); Console.Write(M((true, true))); } private static int M((bool, bool) t) { switch (t) { case (false, false): return 0; case (false, _): return 1; case (_, false): return 2; case (true, true): return 3; case var _: return 4; } } } namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } } }"; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (20,18): error CS8120: The switch case is unreachable. It has already been handled by a previous case or it is impossible to match. // case var _: return 4; Diagnostic(ErrorCode.ERR_SwitchCaseSubsumed, "var _").WithLocation(20, 18) ); } [Fact] public void Patterns2_12() { var source = @" using System; class Program { public static void Main() { Console.Write(M((false, false))); Console.Write(M((false, true))); Console.Write(M((true, false))); Console.Write(M((true, true))); } private static int M((bool, bool) t) { return t switch { (false, false) => 0, (false, _) => 1, (_, false) => 2, _ => 3 }; } } namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } } }"; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: @"0123"); } [Fact] public void SwitchArmSubsumed() { var source = @"public class X { public static void Main() { string s = string.Empty; string s2 = s switch { null => null, string t => t, ""foo"" => null }; } }"; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (6,61): error CS8410: The pattern is unreachable. It has already been handled by a previous arm of the switch expression or it is impossible to match. // string s2 = s switch { null => null, string t => t, "foo" => null }; Diagnostic(ErrorCode.ERR_SwitchArmSubsumed, @"""foo""").WithLocation(6, 61) ); } [Fact] public void LongTuples() { var source = @"using System; public class X { public static void Main() { var t = (1, 2, 3, 4, 5, 6, 7, 8, 9); { Console.WriteLine(t is (_, _, _, _, _, _, _, _, var t9) ? t9 : 100); } switch (t) { case (_, _, _, _, _, _, _, _, var t9): Console.WriteLine(t9); break; } Console.WriteLine(t switch { (_, _, _, _, _, _, _, _, var t9) => t9 }); } }"; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: @"9 9 9"); } [Fact] public void TypeCheckInPropertyPattern() { var source = @"using System; class Program2 { public static void Main() { object o = new Frog(1, 2); if (o is Frog(1, 2)) { Console.Write(1); } if (o is Frog { A: 1, B: 2 }) { Console.Write(2); } if (o is Frog(1, 2) { A: 1, B: 2, C: 3 }) { Console.Write(3); } if (o is Frog(9, 2) { A: 1, B: 2, C: 3 }) {} else { Console.Write(4); } if (o is Frog(1, 9) { A: 1, B: 2, C: 3 }) {} else { Console.Write(5); } if (o is Frog(1, 2) { A: 9, B: 2, C: 3 }) {} else { Console.Write(6); } if (o is Frog(1, 2) { A: 1, B: 9, C: 3 }) {} else { Console.Write(7); } if (o is Frog(1, 2) { A: 1, B: 2, C: 9 }) {} else { Console.Write(8); } } } class Frog { public object A, B; public object C => (int)A + (int)B; public Frog(object A, object B) => (this.A, this.B) = (A, B); public void Deconstruct(out object A, out object B) => (A, B) = (this.A, this.B); } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: @"12345678"); } [Fact] public void OvereagerSubsumption() { var source = @"class Program2 { public static int Main() => 0; public static void M(object o) { switch (o) { case (1, 2): break; case string s: break; } } } "; var compilation = CreateCompilationWithMscorlib45(source); // doesn't have ITuple // Two errors below instead of one due to https://github.com/dotnet/roslyn/issues/25533 compilation.VerifyDiagnostics( // (8,18): error CS1061: 'object' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // case (1, 2): Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "(1, 2)").WithArguments("object", "Deconstruct").WithLocation(8, 18), // (8,18): error CS8129: No suitable Deconstruct instance or extension method was found for type 'object', with 2 out parameters and a void return type. // case (1, 2): Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(1, 2)").WithArguments("object", "2").WithLocation(8, 18) ); } [Fact] public void UnderscoreDeclaredAndDiscardPattern_01() { var source = @"class Program0 { static int Main() => 0; private const int _ = 1; bool M1(object o) => o is _; bool M2(object o) => o switch { 1 => true, _ => false }; } class Program1 { class _ {} bool M3(object o) => o is _; bool M4(object o) => o switch { 1 => true, _ => false }; } "; var expected = new[] { // (5,31): error CS0246: The type or namespace name '_' could not be found (are you missing a using directive or an assembly reference?) // bool M1(object o) => o is _; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "_").WithArguments("_").WithLocation(5, 31), // (11,31): warning CS8513: The name '_' refers to the type 'Program1._', not the discard pattern. Use '@_' for the type, or 'var _' to discard. // bool M3(object o) => o is _; Diagnostic(ErrorCode.WRN_IsTypeNamedUnderscore, "_").WithArguments("Program1._").WithLocation(11, 31) }; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics(expected); compilation = CreateCompilation(source, parseOptions: TestOptions.Regular8); compilation.VerifyDiagnostics(expected); expected = new[] { // (5,31): error CS0246: The type or namespace name '_' could not be found (are you missing a using directive or an assembly reference?) // bool M1(object o) => o is _; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "_").WithArguments("_").WithLocation(5, 31), // (6,26): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // bool M2(object o) => o switch { 1 => true, _ => false }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "o switch { 1 => true, _ => false }").WithArguments("recursive patterns", "8.0").WithLocation(6, 26), // (12,26): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // bool M4(object o) => o switch { 1 => true, _ => false }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "o switch { 1 => true, _ => false }").WithArguments("recursive patterns", "8.0").WithLocation(12, 26) }; compilation = CreateCompilation(source, parseOptions: TestOptions.Regular7_3); compilation.VerifyDiagnostics(expected); } [Fact] public void UnderscoreDeclaredAndDiscardPattern_02() { var source = @"class Program0 { static int Main() => 0; private const int _ = 1; } class Program1 : Program0 { bool M2(object o) => o switch { 1 => true, _ => false }; // ok, private member not inherited } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( ); } [Fact] public void UnderscoreDeclaredAndDiscardPattern_03() { var source = @"class Program0 { static int Main() => 0; protected const int _ = 1; } class Program1 : Program0 { bool M2(object o) => o switch { 1 => true, _ => false }; } class Program2 { bool _(object q) => true; bool M2(object o) => o switch { 1 => true, _ => false }; } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( ); } [Fact] public void UnderscoreDeclaredAndDiscardPattern_04() { var source = @"using _ = System.Int32; class Program { static int Main() => 0; bool M2(object o) => o switch { 1 => true, _ => false }; } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (1,1): hidden CS8019: Unnecessary using directive. // using _ = System.Int32; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using _ = System.Int32;").WithLocation(1, 1) ); } [Fact] public void EscapingUnderscoreDeclaredAndDiscardPattern_04() { var source = @"class Program0 { static int Main() => 0; private const int _ = 2; bool M1(object o) => o is @_; int M2(object o) => o switch { 1 => 1, @_ => 2, var _ => 3 }; } class Program1 { class _ {} bool M1(object o) => o is @_; } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( ); } [Fact] public void ErroneousSwitchArmDefiniteAssignment() { // When a switch expression arm is erroneous, ensure that the expression is treated as unreachable (e.g. for definite assignment purposes). var source = @"class Program2 { public static int Main() => 0; public static void M(string s) { int i; int j = s switch { ""frog"" => 1, 0 => i, _ => 2 }; } } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (7,41): error CS0029: Cannot implicitly convert type 'int' to 'string' // int j = s switch { "frog" => 1, 0 => i, _ => 2 }; Diagnostic(ErrorCode.ERR_NoImplicitConv, "0").WithArguments("int", "string").WithLocation(7, 41) ); } [Fact, WorkItem(9154, "https://github.com/dotnet/roslyn/issues/9154")] public void ErroneousIsPatternDefiniteAssignment() { var source = @"class Program2 { public static int Main() => 0; void Dummy(object o) {} void Test5() { Dummy((System.Func<object, object, bool>) ((o1, o2) => o1 is int x5 && o2 is int x5 && x5 > 0)); } } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (8,74): error CS0128: A local variable or function named 'x5' is already defined in this scope // o2 is int x5 && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(8, 74) ); } [Fact] public void ERR_IsPatternImpossible() { var source = @"class Program { public static void Main() { System.Console.WriteLine(""frog"" is string { Length: 4, Length: 5 }); } } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (5,34): error CS8415: An expression of type 'string' can never match the provided pattern. // System.Console.WriteLine("frog" is string { Length: 4, Length: 5 }); Diagnostic(ErrorCode.ERR_IsPatternImpossible, @"""frog"" is string { Length: 4, Length: 5 }").WithArguments("string").WithLocation(5, 34) ); } [Fact] public void WRN_GivenExpressionNeverMatchesPattern01() { var source = @"class Program { public static void Main() { System.Console.WriteLine(3 is 4); } } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (5,34): warning CS8416: The given expression never matches the provided pattern. // System.Console.WriteLine(3 is 4); Diagnostic(ErrorCode.WRN_GivenExpressionNeverMatchesPattern, "3 is 4").WithLocation(5, 34) ); } [Fact] public void WRN_GivenExpressionNeverMatchesPattern02() { var source = @"class Program { public static void Main() { const string s = null; System.Console.WriteLine(s is string { Length: 3 }); } } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (6,34): warning CS8416: The given expression never matches the provided pattern. // System.Console.WriteLine(s is string { Length: 3 }); Diagnostic(ErrorCode.WRN_GivenExpressionNeverMatchesPattern, "s is string { Length: 3 }").WithLocation(6, 34) ); } [Fact] public void DefiniteAssignmentForIsPattern01() { var source = @"class Program { public static void Main() { string s = 300.ToString(); System.Console.WriteLine(s is string { Length: int j }); System.Console.WriteLine(j); } } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (7,34): error CS0165: Use of unassigned local variable 'j' // System.Console.WriteLine(j); Diagnostic(ErrorCode.ERR_UseDefViolation, "j").WithArguments("j").WithLocation(7, 34) ); } [Fact] public void DefiniteAssignmentForIsPattern02() { var source = @"class Program { public static void Main() { const string s = ""300""; System.Console.WriteLine(s is string { Length: int j }); System.Console.WriteLine(j); } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularWithRecursivePatterns); compilation.VerifyDiagnostics(); var expectedOutput = @"True 3"; var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); } [Fact] public void DefiniteAssignmentForIsPattern03() { var source = @"class Program { public static void Main() { int j; const string s = null; if (s is string { Length: 3 }) { System.Console.WriteLine(j); } } } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (7,13): warning CS8416: The given expression never matches the provided pattern. // if (s is string { Length: 3 }) Diagnostic(ErrorCode.WRN_GivenExpressionNeverMatchesPattern, "s is string { Length: 3 }").WithLocation(7, 13) ); } [Fact] public void RefutableConstantPattern01() { var source = @"class Program { public static void Main() { int j; const int N = 3; const int M = 3; if (N is M) { } else { System.Console.WriteLine(j); } } } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (8,13): warning CS8417: The given expression always matches the provided constant. // if (N is M) Diagnostic(ErrorCode.WRN_GivenExpressionAlwaysMatchesConstant, "N is M").WithLocation(8, 13) ); } [Fact, WorkItem(25591, "https://github.com/dotnet/roslyn/issues/25591")] public void TupleSubsumptionError() { var source = @"class Program2 { public static void Main() { M(new Fox()); M(new Cat()); M(new Program2()); } static void M(object o) { switch ((o, 0)) { case (Fox fox, _): System.Console.Write(""Fox ""); break; case (Cat cat, _): System.Console.Write(""Cat""); break; } } } class Fox {} class Cat {} "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: @"Fox Cat"); } [Fact, WorkItem(25934, "https://github.com/dotnet/roslyn/issues/25934")] public void NamesInPositionalPatterns01() { var source = @"class Program { static void Main() { switch (a: 1, b: 2) { case (c: 2, d: 3): // error: c and d not defined break; } } } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (7,19): error CS8416: The name 'c' does not identify tuple element 'Item1'. // case (c: 2, d: 3): // error: c and d not defined Diagnostic(ErrorCode.ERR_TupleElementNameMismatch, "c").WithArguments("c", "Item1").WithLocation(7, 19), // (7,25): error CS8416: The name 'd' does not identify tuple element 'Item2'. // case (c: 2, d: 3): // error: c and d not defined Diagnostic(ErrorCode.ERR_TupleElementNameMismatch, "d").WithArguments("d", "Item2").WithLocation(7, 25) ); } [Fact, WorkItem(25934, "https://github.com/dotnet/roslyn/issues/25934")] public void NamesInPositionalPatterns02() { var source = @"class Program { static void Main() { switch (a: 1, b: 2) { case (a: 2, a: 3): break; } } } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (7,25): error CS8416: The name 'a' does not identify tuple element 'Item2'. // case (a: 2, a: 3): Diagnostic(ErrorCode.ERR_TupleElementNameMismatch, "a").WithArguments("a", "Item2").WithLocation(7, 25) ); } [Fact, WorkItem(25934, "https://github.com/dotnet/roslyn/issues/25934")] public void NamesInPositionalPatterns03() { var source = @"class Program { static void Main() { switch (a: 1, b: 2) { case (a: 2, Item2: 3): System.Console.WriteLine(666); break; case (a: 1, Item2: 2): System.Console.WriteLine(111); break; } } } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: @"111"); } [Fact, WorkItem(25934, "https://github.com/dotnet/roslyn/issues/25934")] public void NamesInPositionalPatterns04() { var source = @"class Program { static void Main() { switch (new T(a: 1, b: 2)) { case (c: 2, d: 3): break; } } } class T { public int A; public int B; public T(int a, int b) => (A, B) = (a, b); public void Deconstruct(out int a, out int b) => (a, b) = (A, B); } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (7,19): error CS8417: The name 'c' does not match the corresponding 'Deconstruct' parameter 'a'. // case (c: 2, d: 3): Diagnostic(ErrorCode.ERR_DeconstructParameterNameMismatch, "c").WithArguments("c", "a").WithLocation(7, 19), // (7,25): error CS8417: The name 'd' does not match the corresponding 'Deconstruct' parameter 'b'. // case (c: 2, d: 3): Diagnostic(ErrorCode.ERR_DeconstructParameterNameMismatch, "d").WithArguments("d", "b").WithLocation(7, 25) ); } [Fact, WorkItem(25934, "https://github.com/dotnet/roslyn/issues/25934")] public void NamesInPositionalPatterns05() { var source = @"class Program { static void Main() { switch (new T(a: 1, b: 2)) { case (c: 2, d: 3): break; } } } class T { public int A; public int B; public T(int a, int b) => (A, B) = (a, b); } static class Extensions { public static void Deconstruct(this T t, out int a, out int b) => (a, b) = (t.A, t.B); } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (7,19): error CS8417: The name 'c' does not match the corresponding 'Deconstruct' parameter 'a'. // case (c: 2, d: 3): Diagnostic(ErrorCode.ERR_DeconstructParameterNameMismatch, "c").WithArguments("c", "a").WithLocation(7, 19), // (7,25): error CS8417: The name 'd' does not match the corresponding 'Deconstruct' parameter 'b'. // case (c: 2, d: 3): Diagnostic(ErrorCode.ERR_DeconstructParameterNameMismatch, "d").WithArguments("d", "b").WithLocation(7, 25) ); } [Fact, WorkItem(25934, "https://github.com/dotnet/roslyn/issues/25934")] public void NamesInPositionalPatterns06() { var source = @"class Program { static void Main() { switch (new T(a: 1, b: 2)) { case (a: 2, a: 3): break; } } } class T { public int A; public int B; public T(int a, int b) => (A, B) = (a, b); public void Deconstruct(out int a, out int b) => (a, b) = (A, B); } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (7,25): error CS8417: The name 'a' does not match the corresponding 'Deconstruct' parameter 'b'. // case (a: 2, a: 3): Diagnostic(ErrorCode.ERR_DeconstructParameterNameMismatch, "a").WithArguments("a", "b").WithLocation(7, 25) ); } [Fact, WorkItem(25934, "https://github.com/dotnet/roslyn/issues/25934")] public void NamesInPositionalPatterns07() { var source = @"class Program { static void Main() { switch (new T(a: 1, b: 2)) { case (a: 2, a: 3): break; } } } class T { public int A; public int B; public T(int a, int b) => (A, B) = (a, b); } static class Extensions { public static void Deconstruct(this T t, out int a, out int b) => (a, b) = (t.A, t.B); } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (7,25): error CS8417: The name 'a' does not match the corresponding 'Deconstruct' parameter 'b'. // case (a: 2, a: 3): Diagnostic(ErrorCode.ERR_DeconstructParameterNameMismatch, "a").WithArguments("a", "b").WithLocation(7, 25) ); } [Fact, WorkItem(25934, "https://github.com/dotnet/roslyn/issues/25934")] public void NamesInPositionalPatterns08() { var source = @"class Program { static void Main() { switch (new T(a: 1, b: 2)) { case (a: 2, b: 3): System.Console.WriteLine(666); break; case (a: 1, b: 2): System.Console.WriteLine(111); break; } } } class T { public int A; public int B; public T(int a, int b) => (A, B) = (a, b); public void Deconstruct(out int a, out int b) => (a, b) = (A, B); } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: @"111"); } [Fact, WorkItem(25934, "https://github.com/dotnet/roslyn/issues/25934")] public void NamesInPositionalPatterns09() { var source = @"class Program { static void Main() { switch (new T(a: 1, b: 2)) { case (a: 2, b: 3): System.Console.WriteLine(666); break; case (a: 1, b: 2): System.Console.WriteLine(111); break; } } } class T { public int A; public int B; public T(int a, int b) => (A, B) = (a, b); } static class Extensions { public static void Deconstruct(this T t, out int a, out int b) => (a, b) = (t.A, t.B); } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: @"111"); } [Fact, WorkItem(25934, "https://github.com/dotnet/roslyn/issues/25934")] public void NamesInPositionalPatterns10() { var source = @"class Program { static void Main() { switch (a: 1, b: 2) { case (Item2: 1, 2): break; } } } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (7,19): error CS8416: The name 'Item2' does not identify tuple element 'Item1'. // case (Item2: 1, 2): Diagnostic(ErrorCode.ERR_TupleElementNameMismatch, "Item2").WithArguments("Item2", "Item1").WithLocation(7, 19) ); } [Fact] public void PropertyPatternMemberMissing01() { var source = @"class Program { static void Main(string[] args) { Blah b = null; if (b is Blah { X: int i }) { } } } class Blah { }"; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (6,25): error CS0117: 'Blah' does not contain a definition for 'X' // if (b is Blah { X: int i }) Diagnostic(ErrorCode.ERR_NoSuchMember, "X").WithArguments("Blah", "X").WithLocation(6, 25) ); } [Fact] public void PropertyPatternMemberMissing02() { var source = @"class Program { static void Main(string[] args) { Blah b = null; if (b is Blah { X: int i }) { } } } class Blah { public int X { set {} } }"; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (6,25): error CS0154: The property or indexer 'Blah.X' cannot be used in this context because it lacks the get accessor // if (b is Blah { X: int i }) Diagnostic(ErrorCode.ERR_PropertyLacksGet, "X:").WithArguments("Blah.X").WithLocation(6, 25) ); } [Fact] public void PropertyPatternMemberMissing03() { var source = @"class Program { static void Main(string[] args) { Blah b = null; switch (b) { case Blah { X: int i }: break; } } } class Blah { }"; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (8,25): error CS0117: 'Blah' does not contain a definition for 'X' // case Blah { X: int i }: Diagnostic(ErrorCode.ERR_NoSuchMember, "X").WithArguments("Blah", "X").WithLocation(8, 25) ); } [Fact] public void PropertyPatternMemberMissing04() { var source = @"class Program { static void Main(string[] args) { Blah b = null; switch (b) { case Blah { X: int i }: break; } } } class Blah { public int X { set {} } }"; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (8,25): error CS0154: The property or indexer 'Blah.X' cannot be used in this context because it lacks the get accessor // case Blah { X: int i }: Diagnostic(ErrorCode.ERR_PropertyLacksGet, "X:").WithArguments("Blah.X").WithLocation(8, 25) ); } [Fact] [WorkItem(24550, "https://github.com/dotnet/roslyn/issues/24550")] [WorkItem(1284, "https://github.com/dotnet/csharplang/issues/1284")] public void ConstantPatternVsUnconstrainedTypeParameter03() { var source = @"class C<T> { internal struct S { } static bool Test(S s) { return s is null; } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics( // (6,21): error CS0037: Cannot convert null to 'C<T>.S' because it is a non-nullable value type // return s is null; Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("C<T>.S").WithLocation(6, 21) ); } [Fact] [WorkItem(24550, "https://github.com/dotnet/roslyn/issues/24550")] [WorkItem(1284, "https://github.com/dotnet/csharplang/issues/1284")] public void ConstantPatternVsUnconstrainedTypeParameter04() { var source = @"class C<T> { static bool Test(C<T> x) { return x is 1; } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics( // (5,21): error CS8121: An expression of type 'C<T>' cannot be handled by a pattern of type 'int'. // return x is 1; Diagnostic(ErrorCode.ERR_PatternWrongType, "1").WithArguments("C<T>", "int").WithLocation(5, 21) ); } [Fact] [WorkItem(20724, "https://github.com/dotnet/roslyn/issues/20724")] public void SpeculateWithNameConflict01() { var source = @"public class Class1 { int i = 1; public override int GetHashCode() => 1; public override bool Equals(object obj) { return obj is global::Class1 @class && this.i == @class.i; } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics( ); var tree = compilation.SyntaxTrees[0]; var model = (CSharpSemanticModel)compilation.GetSemanticModel(tree); var returnStatement = tree.GetRoot().DescendantNodes().OfType<ReturnStatementSyntax>().Single(); Assert.Equal("return obj is global::Class1 @class && this.i == @class.i;", returnStatement.ToString()); var modifiedReturnStatement = (ReturnStatementSyntax)new RemoveAliasQualifiers().Visit(returnStatement); Assert.Equal("return obj is Class1 @class && this.i == @class.i;", modifiedReturnStatement.ToString()); var gotModel = model.TryGetSpeculativeSemanticModel(returnStatement.Location.SourceSpan.Start, modifiedReturnStatement, out var speculativeModel); Assert.True(gotModel); Assert.NotNull(speculativeModel); var typeInfo = speculativeModel.GetTypeInfo(modifiedReturnStatement.Expression); Assert.Equal(SpecialType.System_Boolean, typeInfo.Type.SpecialType); } /// <summary> /// Helper class to remove alias qualifications. /// </summary> class RemoveAliasQualifiers : CSharpSyntaxRewriter { public override SyntaxNode VisitAliasQualifiedName(AliasQualifiedNameSyntax node) { return node.Name; } } [Fact] [WorkItem(20724, "https://github.com/dotnet/roslyn/issues/20724")] public void SpeculateWithNameConflict02() { var source = @"public class Class1 { public override int GetHashCode() => 1; public override bool Equals(object obj) { return obj is global::Class1 @class; } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics( ); var tree = compilation.SyntaxTrees[0]; var model = (CSharpSemanticModel)compilation.GetSemanticModel(tree); var returnStatement = tree.GetRoot().DescendantNodes().OfType<ReturnStatementSyntax>().Single(); Assert.Equal("return obj is global::Class1 @class;", returnStatement.ToString()); var modifiedReturnStatement = (ReturnStatementSyntax)new RemoveAliasQualifiers().Visit(returnStatement); Assert.Equal("return obj is Class1 @class;", modifiedReturnStatement.ToString()); var gotModel = model.TryGetSpeculativeSemanticModel(returnStatement.Location.SourceSpan.Start, modifiedReturnStatement, out var speculativeModel); Assert.True(gotModel); Assert.NotNull(speculativeModel); var typeInfo = speculativeModel.GetTypeInfo(modifiedReturnStatement.Expression); Assert.Equal(SpecialType.System_Boolean, typeInfo.Type.SpecialType); } [Fact] public void WrongArity() { var source = @"class Program { static void Main(string[] args) { Point p = new Point() { X = 3, Y = 4 }; if (p is Point()) { } } } class Point { public int X, Y; public void Deconstruct(out int X, out int Y) => (X, Y) = (this.X, this.Y); } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics( // (6,23): error CS7036: There is no argument given that corresponds to the required formal parameter 'X' of 'Point.Deconstruct(out int, out int)' // if (p is Point()) Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "()").WithArguments("X", "Point.Deconstruct(out int, out int)").WithLocation(6, 23), // (6,23): error CS8129: No suitable Deconstruct instance or extension method was found for type 'Point', with 0 out parameters and a void return type. // if (p is Point()) Diagnostic(ErrorCode.ERR_MissingDeconstruct, "()").WithArguments("Point", "0").WithLocation(6, 23) ); } [Fact] public void GetTypeInfo_01() { var source = @"class Program { static void Main(string[] args) { object o = null; Point p = null; if (o is Point(3, string { Length: 2 })) { } if (p is (_, { })) { } if (p is Point({ }, { }, { })) { } if (p is Point(, { })) { } } } class Point { public object X, Y; public void Deconstruct(out object X, out object Y) => (X, Y) = (this.X, this.Y); public Point(object X, object Y) => (this.X, this.Y) = (X, Y); } "; var expected = new[] { new { Source = "Point(3, string { Length: 2 })", Type = "System.Object", ConvertedType = "Point" }, new { Source = "3", Type = "System.Object", ConvertedType = "System.Int32" }, new { Source = "string { Length: 2 }", Type = "System.Object", ConvertedType = "System.String" }, new { Source = "2", Type = "System.Int32", ConvertedType = "System.Int32" }, new { Source = "(_, { })", Type = "Point", ConvertedType = "Point" }, new { Source = "_", Type = "System.Object", ConvertedType = "System.Object" }, new { Source = "{ }", Type = "System.Object", ConvertedType = "System.Object" }, new { Source = "Point({ }, { }, { })", Type = "Point", ConvertedType = "Point" }, new { Source = "{ }", Type = "?", ConvertedType = "?" }, new { Source = "{ }", Type = "?", ConvertedType = "?" }, new { Source = "{ }", Type = "?", ConvertedType = "?" }, new { Source = "Point(, { })", Type = "Point", ConvertedType = "Point" }, new { Source = "", Type = "System.Object", ConvertedType = "System.Object" }, new { Source = "{ }", Type = "System.Object", ConvertedType = "System.Object" }, }; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics( // (10,24): error CS8504: Pattern missing // if (p is Point(, { })) { } Diagnostic(ErrorCode.ERR_MissingPattern, ",").WithLocation(10, 24), // (9,23): error CS1501: No overload for method 'Deconstruct' takes 3 arguments // if (p is Point({ }, { }, { })) { } Diagnostic(ErrorCode.ERR_BadArgCount, "({ }, { }, { })").WithArguments("Deconstruct", "3").WithLocation(9, 23), // (9,23): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'Point', with 3 out parameters and a void return type. // if (p is Point({ }, { }, { })) { } Diagnostic(ErrorCode.ERR_MissingDeconstruct, "({ }, { }, { })").WithArguments("Point", "3").WithLocation(9, 23) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); int i = 0; foreach (var pat in tree.GetRoot().DescendantNodesAndSelf().OfType<PatternSyntax>()) { var typeInfo = model.GetTypeInfo(pat); var ex = expected[i++]; Assert.Equal(ex.Source, pat.ToString()); Assert.Equal(ex.Type, typeInfo.Type.ToTestDisplayString()); Assert.Equal(ex.ConvertedType, typeInfo.ConvertedType.ToTestDisplayString()); } Assert.Equal(expected.Length, i); } [Fact, WorkItem(26613, "https://github.com/dotnet/roslyn/issues/26613")] public void MissingDeconstruct_01() { var source = @"using System; public class C { public void M() { _ = this is (a: 1); } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics( // (4,21): error CS1061: 'C' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?) // _ = this is (a: 1); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "(a: 1)").WithArguments("C", "Deconstruct").WithLocation(4, 21), // (4,21): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'C', with 1 out parameters and a void return type. // _ = this is (a: 1); Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(a: 1)").WithArguments("C", "1").WithLocation(4, 21) ); } [Fact, WorkItem(26613, "https://github.com/dotnet/roslyn/issues/26613")] public void MissingDeconstruct_02() { var source = @"using System; public class C { public void M() { _ = this is C(a: 1); } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics( // (4,22): error CS1061: 'C' does not contain a definition for 'Deconstruct' and no extension method 'Deconstruct' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?) // _ = this is C(a: 1); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "(a: 1)").WithArguments("C", "Deconstruct").WithLocation(4, 22), // (4,22): error CS8129: No suitable Deconstruct instance or extension method was found for type 'C', with 1 out parameters and a void return type. // _ = this is C(a: 1); Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(a: 1)").WithArguments("C", "1").WithLocation(4, 22) ); } [Fact] public void PatternTypeInfo_01() { var source = @" public class C { void M(T1 t1) { if (t1 is T2 (var t3, t4: T4 t4) { V5 : T6 t5 }) {} } } class T1 { } class T2 : T1 { public T5 V5 = null; public void Deconstruct(out T3 t3, out T4 t4) => throw null; } class T3 { } class T4 { } class T5 { } class T6 : T5 { } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var patterns = tree.GetRoot().DescendantNodesAndSelf().OfType<PatternSyntax>().ToArray(); Assert.Equal(4, patterns.Length); Assert.Equal("T2 (var t3, t4: T4 t4) { V5 : T6 t5 }", patterns[0].ToString()); var ti = model.GetTypeInfo(patterns[0]); Assert.Equal("T1", ti.Type.ToTestDisplayString()); Assert.Equal("T2", ti.ConvertedType.ToTestDisplayString()); Assert.Equal("var t3", patterns[1].ToString()); ti = model.GetTypeInfo(patterns[1]); Assert.Equal("T3", ti.Type.ToTestDisplayString()); Assert.Equal("T3", ti.ConvertedType.ToTestDisplayString()); Assert.Equal("T4 t4", patterns[2].ToString()); ti = model.GetTypeInfo(patterns[2]); Assert.Equal("T4", ti.Type.ToTestDisplayString()); Assert.Equal("T4", ti.ConvertedType.ToTestDisplayString()); Assert.Equal("T6 t5", patterns[3].ToString()); ti = model.GetTypeInfo(patterns[3]); Assert.Equal("T5", ti.Type.ToTestDisplayString()); Assert.Equal("T6", ti.ConvertedType.ToTestDisplayString()); } [Fact] public void PatternTypeInfo_02() { var source = @" public class C { void M(object o) { if (o is Point(3, 4.0)) {} } } class Point { public void Deconstruct(out object o1, out System.IComparable o2) => throw null; } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var patterns = tree.GetRoot().DescendantNodesAndSelf().OfType<PatternSyntax>().ToArray(); Assert.Equal(3, patterns.Length); Assert.Equal("Point(3, 4.0)", patterns[0].ToString()); var ti = model.GetTypeInfo(patterns[0]); Assert.Equal("System.Object", ti.Type.ToTestDisplayString()); Assert.Equal("Point", ti.ConvertedType.ToTestDisplayString()); Assert.Equal("3", patterns[1].ToString()); ti = model.GetTypeInfo(patterns[1]); Assert.Equal("System.Object", ti.Type.ToTestDisplayString()); Assert.Equal("System.Int32", ti.ConvertedType.ToTestDisplayString()); Assert.Equal("4.0", patterns[2].ToString()); ti = model.GetTypeInfo(patterns[2]); Assert.Equal("System.IComparable", ti.Type.ToTestDisplayString()); Assert.Equal("System.Double", ti.ConvertedType.ToTestDisplayString()); } [Fact] public void PatternTypeInfo_03() { var source = @" public class C { void M(object o) { if (o is Point(3, 4.0) { Missing: Xyzzy }) {} if (o is Q7 t) {} } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,18): error CS0246: The type or namespace name 'Point' could not be found (are you missing a using directive or an assembly reference?) // if (o is Point(3, 4.0) { Missing: Xyzzy }) {} Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Point").WithArguments("Point").WithLocation(6, 18), // (6,43): error CS0103: The name 'Xyzzy' does not exist in the current context // if (o is Point(3, 4.0) { Missing: Xyzzy }) {} Diagnostic(ErrorCode.ERR_NameNotInContext, "Xyzzy").WithArguments("Xyzzy").WithLocation(6, 43), // (7,18): error CS0246: The type or namespace name 'Q7' could not be found (are you missing a using directive or an assembly reference?) // if (o is Q7 t) {} Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Q7").WithArguments("Q7").WithLocation(7, 18) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var patterns = tree.GetRoot().DescendantNodesAndSelf().OfType<PatternSyntax>().ToArray(); Assert.Equal(5, patterns.Length); Assert.Equal("Point(3, 4.0) { Missing: Xyzzy }", patterns[0].ToString()); var ti = model.GetTypeInfo(patterns[0]); Assert.Equal("System.Object", ti.Type.ToTestDisplayString()); Assert.Equal("Point", ti.ConvertedType.ToTestDisplayString()); Assert.Equal("3", patterns[1].ToString()); ti = model.GetTypeInfo(patterns[1]); Assert.Equal("?", ti.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Error, ti.Type.TypeKind); Assert.Equal("System.Int32", ti.ConvertedType.ToTestDisplayString()); Assert.Equal("4.0", patterns[2].ToString()); ti = model.GetTypeInfo(patterns[2]); Assert.Equal("?", ti.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Error, ti.Type.TypeKind); Assert.Equal("System.Double", ti.ConvertedType.ToTestDisplayString()); Assert.Equal("Xyzzy", patterns[3].ToString()); ti = model.GetTypeInfo(patterns[3]); Assert.Equal("?", ti.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Error, ti.Type.TypeKind); Assert.Equal("?", ti.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Error, ti.ConvertedType.TypeKind); Assert.Equal("Q7 t", patterns[4].ToString()); ti = model.GetTypeInfo(patterns[4]); Assert.Equal("System.Object", ti.Type.ToTestDisplayString()); Assert.Equal("Q7", ti.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Error, ti.ConvertedType.TypeKind); } [Fact] [WorkItem(34678, "https://github.com/dotnet/roslyn/issues/34678")] public void ConstantPatternVsUnconstrainedTypeParameter05() { var source = @"class C<T> { static bool Test1(T t) { return t is null; // 1 } static bool Test2(C<T> t) { return t is null; // ok } static bool Test3(T t) { return t is 1; // 2 } static bool Test4(T t) { return t is ""frog""; // 3 } }"; CreateCompilation(source, options: TestOptions.ReleaseDll).VerifyDiagnostics(); CreateCompilation(source, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (5,21): error CS8511: An expression of type 'T' cannot be handled by a pattern of type '<null>'. Please use language version '8.0' or greater to match an open type with a constant pattern. // return t is null; // 1 Diagnostic(ErrorCode.ERR_ConstantPatternVsOpenType, "null").WithArguments("T", "<null>", "8.0").WithLocation(5, 21), // (13,21): error CS8511: An expression of type 'T' cannot be handled by a pattern of type 'int'. Please use language version '8.0' or greater to match an open type with a constant pattern. // return t is 1; // 2 Diagnostic(ErrorCode.ERR_ConstantPatternVsOpenType, "1").WithArguments("T", "int", "8.0").WithLocation(13, 21), // (17,21): error CS8511: An expression of type 'T' cannot be handled by a pattern of type 'string'. Please use language version '8.0' or greater to match an open type with a constant pattern. // return t is "frog"; // 3 Diagnostic(ErrorCode.ERR_ConstantPatternVsOpenType, @"""frog""").WithArguments("T", "string", "8.0").WithLocation(17, 21)); } [Fact] [WorkItem(34905, "https://github.com/dotnet/roslyn/issues/34905")] public void ConstantPatternVsUnconstrainedTypeParameter06() { var source = @"public class C<T> { public enum E { V1, V2 } public void M() { switch (default(E)) { case E.V1: break; } } } "; CreateCompilation(source, options: TestOptions.ReleaseDll).VerifyDiagnostics(); CreateCompilation(source, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics(); } [Fact] public void WarnUnmatchedIsRelationalPattern() { var source = @"public class C { public void M() { _ = 1 is < 0; // 1 _ = 1 is < 1; // 2 _ = 1 is < 2; // 3 _ = 1 is <= 0; // 4 _ = 1 is <= 1; // 5 _ = 1 is <= 2; // 6 _ = 1 is > 0; // 7 _ = 1 is > 1; // 8 _ = 1 is > 2; // 9 _ = 1 is >= 0; // 10 _ = 1 is >= 1; // 11 _ = 1 is >= 2; // 12 } } "; CreateCompilation(source, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularWithPatternCombinators).VerifyDiagnostics( // (5,13): warning CS8519: The given expression never matches the provided pattern. // _ = 1 is < 0; // 1 Diagnostic(ErrorCode.WRN_GivenExpressionNeverMatchesPattern, "1 is < 0").WithLocation(5, 13), // (6,13): warning CS8519: The given expression never matches the provided pattern. // _ = 1 is < 1; // 2 Diagnostic(ErrorCode.WRN_GivenExpressionNeverMatchesPattern, "1 is < 1").WithLocation(6, 13), // (7,13): error CS8793: The given expression always matches the provided pattern. // _ = 1 is < 2; // 3 Diagnostic(ErrorCode.WRN_GivenExpressionAlwaysMatchesPattern, "1 is < 2").WithLocation(7, 13), // (8,13): warning CS8519: The given expression never matches the provided pattern. // _ = 1 is <= 0; // 4 Diagnostic(ErrorCode.WRN_GivenExpressionNeverMatchesPattern, "1 is <= 0").WithLocation(8, 13), // (9,13): error CS8793: The given expression always matches the provided pattern. // _ = 1 is <= 1; // 5 Diagnostic(ErrorCode.WRN_GivenExpressionAlwaysMatchesPattern, "1 is <= 1").WithLocation(9, 13), // (10,13): error CS8793: The given expression always matches the provided pattern. // _ = 1 is <= 2; // 6 Diagnostic(ErrorCode.WRN_GivenExpressionAlwaysMatchesPattern, "1 is <= 2").WithLocation(10, 13), // (11,13): error CS8793: The given expression always matches the provided pattern. // _ = 1 is > 0; // 7 Diagnostic(ErrorCode.WRN_GivenExpressionAlwaysMatchesPattern, "1 is > 0").WithLocation(11, 13), // (12,13): warning CS8519: The given expression never matches the provided pattern. // _ = 1 is > 1; // 8 Diagnostic(ErrorCode.WRN_GivenExpressionNeverMatchesPattern, "1 is > 1").WithLocation(12, 13), // (13,13): warning CS8519: The given expression never matches the provided pattern. // _ = 1 is > 2; // 9 Diagnostic(ErrorCode.WRN_GivenExpressionNeverMatchesPattern, "1 is > 2").WithLocation(13, 13), // (14,13): error CS8793: The given expression always matches the provided pattern. // _ = 1 is >= 0; // 10 Diagnostic(ErrorCode.WRN_GivenExpressionAlwaysMatchesPattern, "1 is >= 0").WithLocation(14, 13), // (15,13): error CS8793: The given expression always matches the provided pattern. // _ = 1 is >= 1; // 11 Diagnostic(ErrorCode.WRN_GivenExpressionAlwaysMatchesPattern, "1 is >= 1").WithLocation(15, 13), // (16,13): warning CS8519: The given expression never matches the provided pattern. // _ = 1 is >= 2; // 12 Diagnostic(ErrorCode.WRN_GivenExpressionNeverMatchesPattern, "1 is >= 2").WithLocation(16, 13) ); } [Fact] public void RelationalPatternInSwitchWithConstantControllingExpression() { var source = @"public class C { public void M() { switch (1) { case < 0: break; // 1 case < 1: break; // 2 case < 2: break; case < 3: break; // 3 } } } "; CreateCompilation(source, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularWithPatternCombinators).VerifyDiagnostics( // (7,23): warning CS0162: Unreachable code detected // case < 0: break; // 1 Diagnostic(ErrorCode.WRN_UnreachableCode, "break").WithLocation(7, 23), // (8,23): warning CS0162: Unreachable code detected // case < 1: break; // 2 Diagnostic(ErrorCode.WRN_UnreachableCode, "break").WithLocation(8, 23), // (10,23): warning CS0162: Unreachable code detected // case < 3: break; // 3 Diagnostic(ErrorCode.WRN_UnreachableCode, "break").WithLocation(10, 23) ); } [Fact] public void RelationalPatternInSwitchWithOutOfRangeComparand() { var source = @"public class C { public void M(int i) { switch (i) { case < int.MinValue: break; // 1 case <= int.MinValue: break; case > int.MaxValue: break; // 2 case >= int.MaxValue: break; } } public void M(uint i) { switch (i) { case < 0: break; // 3 case <= 0: break; case > uint.MaxValue: break; // 4 case >= uint.MaxValue: break; } } } "; CreateCompilation(source, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularWithPatternCombinators).VerifyDiagnostics( // (7,18): error CS8120: The switch case is unreachable. It has already been handled by a previous case or it is impossible to match. // case < int.MinValue: break; // 1 Diagnostic(ErrorCode.ERR_SwitchCaseSubsumed, "< int.MinValue").WithLocation(7, 18), // (9,18): error CS8120: The switch case is unreachable. It has already been handled by a previous case or it is impossible to match. // case > int.MaxValue: break; // 2 Diagnostic(ErrorCode.ERR_SwitchCaseSubsumed, "> int.MaxValue").WithLocation(9, 18), // (17,18): error CS8120: The switch case is unreachable. It has already been handled by a previous case or it is impossible to match. // case < 0: break; // 3 Diagnostic(ErrorCode.ERR_SwitchCaseSubsumed, "< 0").WithLocation(17, 18), // (19,18): error CS8120: The switch case is unreachable. It has already been handled by a previous case or it is impossible to match. // case > uint.MaxValue: break; // 4 Diagnostic(ErrorCode.ERR_SwitchCaseSubsumed, "> uint.MaxValue").WithLocation(19, 18) ); } [Fact] public void IsRelationalPatternWithOutOfRangeComparand() { var source = @"public class C { public void M(int i) { _ = i is < int.MinValue; // 1 _ = i is <= int.MinValue; _ = i is > int.MaxValue; // 2 _ = i is >= int.MaxValue; } public void M(uint i) { _ = i is < 0; // 3 _ = i is <= 0; _ = i is > uint.MaxValue; // 4 _ = i is >= uint.MaxValue; } } "; CreateCompilation(source, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularWithPatternCombinators).VerifyDiagnostics( // (5,13): error CS8518: An expression of type 'int' can never match the provided pattern. // _ = i is < int.MinValue; // 1 Diagnostic(ErrorCode.ERR_IsPatternImpossible, "i is < int.MinValue").WithArguments("int").WithLocation(5, 13), // (7,13): error CS8518: An expression of type 'int' can never match the provided pattern. // _ = i is > int.MaxValue; // 2 Diagnostic(ErrorCode.ERR_IsPatternImpossible, "i is > int.MaxValue").WithArguments("int").WithLocation(7, 13), // (12,13): error CS8518: An expression of type 'uint' can never match the provided pattern. // _ = i is < 0; // 3 Diagnostic(ErrorCode.ERR_IsPatternImpossible, "i is < 0").WithArguments("uint").WithLocation(12, 13), // (14,13): error CS8518: An expression of type 'uint' can never match the provided pattern. // _ = i is > uint.MaxValue; // 4 Diagnostic(ErrorCode.ERR_IsPatternImpossible, "i is > uint.MaxValue").WithArguments("uint").WithLocation(14, 13) ); } [Fact] public void IsRelationalPatternWithAlwaysMatchingRange() { var source = @"public class C { public void M(int i) { _ = i is > int.MinValue; _ = i is >= int.MinValue; // 1 _ = i is < int.MaxValue; _ = i is <= int.MaxValue; // 2 } public void M(uint i) { _ = i is > 0; _ = i is >= 0; // 3 _ = i is < uint.MaxValue; _ = i is <= uint.MaxValue; // 4 } } "; CreateCompilation(source, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularWithPatternCombinators).VerifyDiagnostics( // (6,13): warning CS8794: An expression of type 'int' always matches the provided pattern. // _ = i is >= int.MinValue; // 1 Diagnostic(ErrorCode.WRN_IsPatternAlways, "i is >= int.MinValue").WithArguments("int").WithLocation(6, 13), // (8,13): warning CS8794: An expression of type 'int' always matches the provided pattern. // _ = i is <= int.MaxValue; // 2 Diagnostic(ErrorCode.WRN_IsPatternAlways, "i is <= int.MaxValue").WithArguments("int").WithLocation(8, 13), // (13,13): warning CS8794: An expression of type 'uint' always matches the provided pattern. // _ = i is >= 0; // 3 Diagnostic(ErrorCode.WRN_IsPatternAlways, "i is >= 0").WithArguments("uint").WithLocation(13, 13), // (15,13): warning CS8794: An expression of type 'uint' always matches the provided pattern. // _ = i is <= uint.MaxValue; // 4 Diagnostic(ErrorCode.WRN_IsPatternAlways, "i is <= uint.MaxValue").WithArguments("uint").WithLocation(15, 13) ); } [Fact] public void IsImpossiblePatternKinds() { var source = @"public class C { public void M(string s) { _ = s is (System.Delegate); // impossible parenthesized type pattern _ = s is not _; // impossible negated pattern _ = s is ""a"" and ""b""; // impossible conjunctive pattern } } "; CreateCompilation(source, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularWithPatternCombinators).VerifyDiagnostics( // (5,19): error CS8121: An expression of type 'string' cannot be handled by a pattern of type 'Delegate'. // _ = s is (System.Delegate); // impossible parenthesized type pattern Diagnostic(ErrorCode.ERR_PatternWrongType, "System.Delegate").WithArguments("string", "System.Delegate").WithLocation(5, 19), // (6,13): error CS8518: An expression of type 'string' can never match the provided pattern. // _ = s is not _; // impossible negated pattern Diagnostic(ErrorCode.ERR_IsPatternImpossible, "s is not _").WithArguments("string").WithLocation(6, 13), // (7,13): error CS8518: An expression of type 'string' can never match the provided pattern. // _ = s is "a" and "b"; // impossible conjunctive pattern Diagnostic(ErrorCode.ERR_IsPatternImpossible, @"s is ""a"" and ""b""").WithArguments("string").WithLocation(7, 13) ); } [Fact] public void IsNullableReferenceType_01() { var source = @"#nullable enable public class C { public void M1(object o) { var t = o is string? { }; } public void M2(object o) { var t = o is (string? { }); } public void M3(object o) { var t = o is string?; } public void M4(object o) { var t = o is string? _; } public void M5(object o) { var t = o is (string? _); } }"; CreateCompilation(source, parseOptions: TestOptions.RegularWithPatternCombinators).VerifyDiagnostics( // (4,22): error CS8116: It is not legal to use nullable type 'string?' in a pattern; use the underlying type 'string' instead. // var t = o is string? { }; Diagnostic(ErrorCode.ERR_PatternNullableType, "string?").WithArguments("string").WithLocation(4, 22), // (7,23): error CS8116: It is not legal to use nullable type 'string?' in a pattern; use the underlying type 'string' instead. // var t = o is (string? { }); Diagnostic(ErrorCode.ERR_PatternNullableType, "string?").WithArguments("string").WithLocation(7, 23), // (10,22): error CS8650: It is not legal to use nullable reference type 'string?' in an is-type expression; use the underlying type 'string' instead. // var t = o is string?; Diagnostic(ErrorCode.ERR_IsNullableType, "string?").WithArguments("string").WithLocation(10, 22), // (13,30): error CS0103: The name '_' does not exist in the current context // var t = o is string? _; Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(13, 30), // (13,31): error CS1003: Syntax error, ':' expected // var t = o is string? _; Diagnostic(ErrorCode.ERR_SyntaxError, ";").WithArguments(":", ";").WithLocation(13, 31), // (13,31): error CS1525: Invalid expression term ';' // var t = o is string? _; Diagnostic(ErrorCode.ERR_InvalidExprTerm, ";").WithArguments(";").WithLocation(13, 31), // (16,22): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'object', with 2 out parameters and a void return type. // var t = o is (string? _); Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(string? _)").WithArguments("object", "2").WithLocation(16, 22), // (16,29): error CS1003: Syntax error, ',' expected // var t = o is (string? _); Diagnostic(ErrorCode.ERR_SyntaxError, "?").WithArguments(",", "?").WithLocation(16, 29), // (16,31): error CS1003: Syntax error, ',' expected // var t = o is (string? _); Diagnostic(ErrorCode.ERR_SyntaxError, "_").WithArguments(",", "").WithLocation(16, 31) ); } [Fact] public void IsAlwaysPatternKinds() { var source = @"public class C { public void M(string s) { _ = s is (_); // always parenthesized discard pattern _ = s is not System.Delegate; // always negated type pattern _ = s is string or null; // always disjunctive pattern } } "; CreateCompilation(source, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularWithPatternCombinators).VerifyDiagnostics( // (6,22): error CS8121: An expression of type 'string' cannot be handled by a pattern of type 'Delegate'. // _ = s is not System.Delegate; // always negated type pattern Diagnostic(ErrorCode.ERR_PatternWrongType, "System.Delegate").WithArguments("string", "System.Delegate").WithLocation(6, 22), // (7,13): warning CS8794: An expression of type 'string' always matches the provided pattern. // _ = s is string or null; // always disjunctive pattern Diagnostic(ErrorCode.WRN_IsPatternAlways, "s is string or null").WithArguments("string").WithLocation(7, 13) ); } [Fact] public void SemanticModelForSwitchExpression() { var source = @"public class C { void M(int i) { C x0 = i switch // 0 { 0 => new A(), 1 => new B(), _ => throw null, }; _ = i switch // 1 { 0 => new A(), 1 => new B(), _ => throw null, }; D x2 = i switch // 2 { 0 => new A(), 1 => new B(), _ => throw null, }; D x3 = i switch // 3 { 0 => new E(), // 3.1 1 => new F(), // 3.2 _ => throw null, }; C x4 = i switch // 4 { 0 => new A(), 1 => new B(), 2 => new C(), _ => throw null, }; D x5 = i switch // 5 { 0 => new A(), 1 => new B(), 2 => new C(), _ => throw null, }; D x6 = i switch // 6 { 0 => 1, 1 => 2, _ => throw null, }; _ = (C)(i switch // 7 { 0 => new A(), 1 => new B(), _ => throw null, }); _ = (D)(i switch // 8 { 0 => new A(), 1 => new B(), _ => throw null, }); _ = (D)(i switch // 9 { 0 => new E(), // 9.1 1 => new F(), // 9.2 _ => throw null, }); _ = (C)(i switch // 10 { 0 => new A(), 1 => new B(), 2 => new C(), _ => throw null, }); _ = (D)(i switch // 11 { 0 => new A(), 1 => new B(), 2 => new C(), _ => throw null, }); _ = (D)(i switch // 12 { 0 => 1, 1 => 2, _ => throw null, }); } } class A : C { } class B : C { } class D { public static implicit operator D(C c) => throw null; public static implicit operator D(short s) => throw null; } class E { public static implicit operator C(E c) => throw null; } class F { public static implicit operator C(F c) => throw null; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularWithPatternCombinators).VerifyDiagnostics( // (11,15): error CS8506: No best type was found for the switch expression. // _ = i switch // 1 Diagnostic(ErrorCode.ERR_SwitchExpressionNoBestType, "switch").WithLocation(11, 15), // (25,18): error CS0029: Cannot implicitly convert type 'E' to 'D' // 0 => new E(), // 3.1 Diagnostic(ErrorCode.ERR_NoImplicitConv, "new E()").WithArguments("E", "D").WithLocation(25, 18), // (26,18): error CS0029: Cannot implicitly convert type 'F' to 'D' // 1 => new F(), // 3.2 Diagnostic(ErrorCode.ERR_NoImplicitConv, "new F()").WithArguments("F", "D").WithLocation(26, 18), // (63,18): error CS0029: Cannot implicitly convert type 'E' to 'D' // 0 => new E(), // 9.1 Diagnostic(ErrorCode.ERR_NoImplicitConv, "new E()").WithArguments("E", "D").WithLocation(63, 18), // (64,18): error CS0029: Cannot implicitly convert type 'F' to 'D' // 1 => new F(), // 9.2 Diagnostic(ErrorCode.ERR_NoImplicitConv, "new F()").WithArguments("F", "D").WithLocation(64, 18) ); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); void checkType(ExpressionSyntax expr, string expectedNaturalType, string expectedConvertedType, ConversionKind expectedConversionKind) { var typeInfo = model.GetTypeInfo(expr); var conversion = model.GetConversion(expr); Assert.Equal(expectedNaturalType, typeInfo.Type?.ToTestDisplayString()); Assert.Equal(expectedConvertedType, typeInfo.ConvertedType?.ToTestDisplayString()); Assert.Equal(expectedConversionKind, conversion.Kind); } var switches = tree.GetRoot().DescendantNodes().OfType<SwitchExpressionSyntax>().ToArray(); for (int i = 0; i < switches.Length; i++) { var expr = switches[i]; switch (i) { case 0: checkType(expr, null, "C", ConversionKind.SwitchExpression); checkType(expr.Arms[0].Expression, "A", "C", ConversionKind.ImplicitReference); checkType(expr.Arms[1].Expression, "B", "C", ConversionKind.ImplicitReference); checkType(expr.Arms[2].Expression, null, "C", ConversionKind.ImplicitThrow); break; case 1: checkType(expr, "?", "?", ConversionKind.Identity); checkType(expr.Arms[0].Expression, "A", "?", ConversionKind.NoConversion); checkType(expr.Arms[1].Expression, "B", "?", ConversionKind.NoConversion); checkType(expr.Arms[2].Expression, null, "?", ConversionKind.ImplicitThrow); break; case 2: checkType(expr, null, "D", ConversionKind.SwitchExpression); checkType(expr.Arms[0].Expression, "A", "D", ConversionKind.ImplicitUserDefined); checkType(expr.Arms[1].Expression, "B", "D", ConversionKind.ImplicitUserDefined); checkType(expr.Arms[2].Expression, null, "D", ConversionKind.ImplicitThrow); break; case 3: checkType(expr, "?", "D", ConversionKind.NoConversion); checkType(expr.Arms[0].Expression, "E", "?", ConversionKind.NoConversion); checkType(expr.Arms[1].Expression, "F", "?", ConversionKind.NoConversion); checkType(expr.Arms[2].Expression, null, "?", ConversionKind.ImplicitThrow); break; case 4: case 10: checkType(expr, "C", "C", ConversionKind.Identity); checkType(expr.Arms[0].Expression, "A", "C", ConversionKind.ImplicitReference); checkType(expr.Arms[1].Expression, "B", "C", ConversionKind.ImplicitReference); checkType(expr.Arms[2].Expression, "C", "C", ConversionKind.Identity); checkType(expr.Arms[3].Expression, null, "C", ConversionKind.ImplicitThrow); break; case 5: checkType(expr, "C", "D", ConversionKind.ImplicitUserDefined); checkType(expr.Arms[0].Expression, "A", "C", ConversionKind.ImplicitReference); checkType(expr.Arms[1].Expression, "B", "C", ConversionKind.ImplicitReference); checkType(expr.Arms[2].Expression, "C", "C", ConversionKind.Identity); checkType(expr.Arms[3].Expression, null, "C", ConversionKind.ImplicitThrow); break; case 11: checkType(expr, "C", "C", ConversionKind.Identity); checkType(expr.Arms[0].Expression, "A", "C", ConversionKind.ImplicitReference); checkType(expr.Arms[1].Expression, "B", "C", ConversionKind.ImplicitReference); checkType(expr.Arms[2].Expression, "C", "C", ConversionKind.Identity); checkType(expr.Arms[3].Expression, null, "C", ConversionKind.ImplicitThrow); break; case 6: checkType(expr, "System.Int32", "D", ConversionKind.SwitchExpression); checkType(expr.Arms[0].Expression, "System.Int32", "D", ConversionKind.ImplicitUserDefined); checkType(expr.Arms[1].Expression, "System.Int32", "D", ConversionKind.ImplicitUserDefined); checkType(expr.Arms[2].Expression, null, "D", ConversionKind.ImplicitThrow); break; case 7: checkType(expr, null, null, ConversionKind.Identity); checkType(expr.Arms[0].Expression, "A", "C", ConversionKind.ImplicitReference); checkType(expr.Arms[1].Expression, "B", "C", ConversionKind.ImplicitReference); checkType(expr.Arms[2].Expression, null, "C", ConversionKind.ImplicitThrow); checkType((CastExpressionSyntax)expr.Parent.Parent, "C", "C", ConversionKind.Identity); break; case 8: checkType(expr, null, null, ConversionKind.Identity); checkType(expr.Arms[0].Expression, "A", "D", ConversionKind.ImplicitUserDefined); checkType(expr.Arms[1].Expression, "B", "D", ConversionKind.ImplicitUserDefined); checkType(expr.Arms[2].Expression, null, "D", ConversionKind.ImplicitThrow); checkType((CastExpressionSyntax)expr.Parent.Parent, "D", "D", ConversionKind.Identity); break; case 9: checkType(expr, "?", "?", ConversionKind.Identity); checkType(expr.Arms[0].Expression, "E", "?", ConversionKind.NoConversion); checkType(expr.Arms[1].Expression, "F", "?", ConversionKind.NoConversion); checkType(expr.Arms[2].Expression, null, "?", ConversionKind.ImplicitThrow); checkType((CastExpressionSyntax)expr.Parent.Parent, "D", "D", ConversionKind.Identity); break; case 12: checkType(expr, "System.Int32", "System.Int32", ConversionKind.Identity); checkType(expr.Arms[0].Expression, "System.Int32", "D", ConversionKind.ImplicitUserDefined); checkType(expr.Arms[1].Expression, "System.Int32", "D", ConversionKind.ImplicitUserDefined); checkType(expr.Arms[2].Expression, null, "D", ConversionKind.ImplicitThrow); checkType((CastExpressionSyntax)expr.Parent.Parent, "D", "D", ConversionKind.Identity); break; default: Assert.False(true); break; } } } [Fact, WorkItem(45946, "https://github.com/dotnet/roslyn/issues/45946")] public void VoidPattern_01() { var source = @" class C { void F(object o) { _ = is this.F(1); } }"; CreateCompilation(source).VerifyDiagnostics( // (6,13): error CS1525: Invalid expression term 'is' // _ = is this.F(1); Diagnostic(ErrorCode.ERR_InvalidExprTerm, "is").WithArguments("is").WithLocation(6, 13) ); } [Fact, WorkItem(45946, "https://github.com/dotnet/roslyn/issues/45946")] public void VoidPattern_02() { var source = @" class C { void F(object o) { _ = switch { this.F(1) => 1 }; } }"; CreateCompilation(source).VerifyDiagnostics( // (6,13): error CS1525: Invalid expression term 'switch' // _ = switch { this.F(1) => 1 }; Diagnostic(ErrorCode.ERR_InvalidExprTerm, "switch").WithArguments("switch").WithLocation(6, 13), // (6,13): warning CS8848: Operator 'switch' cannot be used here due to precedence. Use parentheses to disambiguate. // _ = switch { this.F(1) => 1 }; Diagnostic(ErrorCode.WRN_PrecedenceInversion, "switch").WithArguments("switch").WithLocation(6, 13) ); } [Fact, WorkItem(48112, "https://github.com/dotnet/roslyn/issues/48112")] public void NullableTypePattern() { var source = @" class C { void F(object o) { _ = o switch { (int?) => 1, _ => 0 }; _ = o switch { int? => 1, _ => 0 }; } }"; CreateCompilation(source).VerifyDiagnostics( // (6,25): error CS8116: It is not legal to use nullable type 'int?' in a pattern; use the underlying type 'int' instead. // _ = o switch { (int?) => 1, _ => 0 }; Diagnostic(ErrorCode.ERR_PatternNullableType, "int?").WithArguments("int").WithLocation(6, 25), // (7,24): error CS8116: It is not legal to use nullable type 'int?' in a pattern; use the underlying type 'int' instead. // _ = o switch { int? => 1, _ => 0 }; Diagnostic(ErrorCode.ERR_PatternNullableType, "int?").WithArguments("int").WithLocation(7, 24) ); } [Fact, WorkItem(55668, "https://github.com/dotnet/roslyn/issues/55668")] public void SharedWhenExpression_SwitchExpression() { var source = @" int count = 0; foreach (var position in new[] { Position.First, Position.Last }) { foreach (var wrap in new[] { new Wrap { Sub = new Zero() }, new Wrap { Sub = new One() }, new Wrap { Sub = new Two() }, new Wrap { Sub = new object() } }) { count++; if (M(position, wrap) != M2(position, wrap)) throw null; } } System.Console.Write(count); static string M(Position position, Wrap wrap) { return position switch { not Position.First when wrap.Sub is Zero => ""Not First and Zero"", _ when wrap is { Sub: One or Two } => ""One or Two"", Position.First => ""First"", _ => ""Other"" }; } static string M2(Position position, Wrap wrap) { if (position is not Position.First && wrap.Sub is Zero) return ""Not First and Zero""; if (wrap is { Sub: One or Two }) return ""One or Two""; if (position is Position.First) return ""First""; return ""Other""; } enum Position { First, Last, } class Zero { } class One { } class Two { } class Wrap { public object Sub; } "; CompileAndVerify(source, expectedOutput: "8"); } [Fact, WorkItem(55668, "https://github.com/dotnet/roslyn/issues/55668")] public void SharedWhenExpression_SwitchStatement() { var source = @" M(Position.Last, new Wrap { Sub = new Zero() }); M(Position.Last, new Wrap { Sub = new One() }); M(Position.Last, new Wrap { Sub = new Two() }); M(Position.First, new Wrap { Sub = new Zero() }); M(Position.Last, new Wrap { Sub = new object() }); static void M(Position position, Wrap wrap) { string text; switch (position) { case not Position.First when wrap.Sub is Zero: text = ""Not First and Zero""; break; case var _ when wrap is { Sub: One or Two }: text = ""One or Two""; break; case Position.First: text = ""First""; break; default: text = ""Other""; break; } System.Console.WriteLine((position, wrap.Sub, text)); } enum Position { First, Last, } class Zero { } class One { } class Two { } class Wrap { public object Sub; } "; CompileAndVerify(source, expectedOutput: @" (Last, Zero, Not First and Zero) (Last, One, One or Two) (Last, Two, One or Two) (First, Zero, First) (Last, System.Object, Other)"); } [Fact, WorkItem(55668, "https://github.com/dotnet/roslyn/issues/55668")] public void SharedWhenExpression_SequencePoints() { var source = @" C.M(0, false, false); C.M(0, true, false); C.M(0, false, true); C.M(1, false, false); C.M(1, false, true); C.M(2, false, false); public class C { public static void M(int i, bool b1, bool b2) { string text; switch (i) { case not 1 when b1: text = ""b1""; break; case var _ when b2: text = ""b2""; break; case 1: text = ""1""; break; default: text = ""default""; break; } System.Console.WriteLine((i, b1, b2, text)); } } "; var verifier = CompileAndVerify(source, expectedOutput: @" (0, False, False, default) (0, True, False, b1) (0, False, True, b2) (1, False, False, 1) (1, False, True, b2) (2, False, False, default) "); verifier.VerifyIL("C.M", @" { // Code size 73 (0x49) .maxstack 4 .locals init (string V_0, //text int V_1) // sequence point: switch (i) IL_0000: ldarg.0 // sequence point: <hidden> IL_0001: ldc.i4.1 IL_0002: beq.s IL_000f // sequence point: when b1 IL_0004: ldarg.1 IL_0005: brfalse.s IL_0013 // sequence point: text = ""b1""; IL_0007: ldstr ""b1"" IL_000c: stloc.0 // sequence point: break; IL_000d: br.s IL_0035 // sequence point: <hidden> IL_000f: ldc.i4.0 IL_0010: stloc.1 IL_0011: br.s IL_0015 IL_0013: ldc.i4.2 IL_0014: stloc.1 // sequence point: when b2 IL_0015: ldarg.2 IL_0016: brtrue.s IL_001f // sequence point: <hidden> IL_0018: ldloc.1 IL_0019: brfalse.s IL_0027 IL_001b: ldloc.1 IL_001c: ldc.i4.2 IL_001d: beq.s IL_002f // sequence point: text = ""b2""; IL_001f: ldstr ""b2"" IL_0024: stloc.0 // sequence point: break; IL_0025: br.s IL_0035 // sequence point: text = ""1""; IL_0027: ldstr ""1"" IL_002c: stloc.0 // sequence point: break; IL_002d: br.s IL_0035 // sequence point: text = ""default""; IL_002f: ldstr ""default"" IL_0034: stloc.0 // sequence point: System.Console.WriteLine((i, b1, b2, text)); IL_0035: ldarg.0 IL_0036: ldarg.1 IL_0037: ldarg.2 IL_0038: ldloc.0 IL_0039: newobj ""System.ValueTuple<int, bool, bool, string>..ctor(int, bool, bool, string)"" IL_003e: box ""System.ValueTuple<int, bool, bool, string>"" IL_0043: call ""void System.Console.WriteLine(object)"" // sequence point: } IL_0048: ret } ", source: source, sequencePoints: "C.M"); } [Fact, WorkItem(55668, "https://github.com/dotnet/roslyn/issues/55668")] public void SharedWhenExpression_MissingInt32Type() { var source = @" class C { static void M(string s, bool b1, bool b2) { switch (s) { case not ""one"" when b1: break; case var _ when b2: break; case ""one"": break; default: break; } } } "; var comp = CreateCompilation(source); comp.MakeTypeMissing(SpecialType.System_Int32); comp.VerifyEmitDiagnostics( // (6,9): error CS0518: Predefined type 'System.Int32' is not defined or imported // switch (s) Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"switch (s) { case not ""one"" when b1: break; case var _ when b2: break; case ""one"": break; default: break; }").WithArguments("System.Int32").WithLocation(6, 9), // (6,9): error CS0518: Predefined type 'System.Int32' is not defined or imported // switch (s) Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"switch (s) { case not ""one"" when b1: break; case var _ when b2: break; case ""one"": break; default: break; }").WithArguments("System.Int32").WithLocation(6, 9), // (8,13): error CS0518: Predefined type 'System.Int32' is not defined or imported // case not "one" when b1: Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"case not ""one"" when b1:").WithArguments("System.Int32").WithLocation(8, 13) ); } [Fact, WorkItem(55668, "https://github.com/dotnet/roslyn/issues/55668")] public void SharedWhenExpression_WithBindings() { var source = @" C.M(""Alice"", false, true); C.M(""Bob"", false, true); public class C { public static void M(string s, bool b1, bool b2) { switch (s) { case not ""x"" when b1: throw null; case { Length: var j and > 2 } when b2: System.Console.WriteLine((s, b1, b2, j.ToString())); break; case ""x"": throw null; default: throw null; } } } "; var verifier = CompileAndVerify(source, expectedOutput: @" (Alice, False, True, 5) (Bob, False, True, 3) "); verifier.VerifyIL("C.M", @" { // Code size 95 (0x5f) .maxstack 4 .locals init (int V_0, int V_1, //j string V_2) // sequence point: switch (s) IL_0000: ldarg.0 IL_0001: stloc.2 // sequence point: <hidden> IL_0002: ldloc.2 IL_0003: ldstr ""x"" IL_0008: call ""bool string.op_Equality(string, string)"" IL_000d: brfalse.s IL_002c IL_000f: ldloc.2 IL_0010: callvirt ""int string.Length.get"" IL_0015: stloc.1 // sequence point: <hidden> IL_0016: ldloc.1 IL_0017: ldc.i4.2 IL_0018: bgt.s IL_0031 IL_001a: br.s IL_005b IL_001c: ldloc.2 IL_001d: brfalse.s IL_005d IL_001f: ldloc.2 IL_0020: callvirt ""int string.Length.get"" IL_0025: stloc.1 // sequence point: <hidden> IL_0026: ldloc.1 IL_0027: ldc.i4.2 IL_0028: bgt.s IL_0035 IL_002a: br.s IL_005d // sequence point: when b1 IL_002c: ldarg.1 IL_002d: brfalse.s IL_001c // sequence point: throw null; IL_002f: ldnull IL_0030: throw // sequence point: <hidden> IL_0031: ldc.i4.0 IL_0032: stloc.0 IL_0033: br.s IL_0037 IL_0035: ldc.i4.2 IL_0036: stloc.0 // sequence point: when b2 IL_0037: ldarg.2 IL_0038: brtrue.s IL_0041 // sequence point: <hidden> IL_003a: ldloc.0 IL_003b: brfalse.s IL_005b IL_003d: ldloc.0 IL_003e: ldc.i4.2 IL_003f: beq.s IL_005d // sequence point: System.Console.WriteLine((s, b1, b2, j.ToString())); IL_0041: ldarg.0 IL_0042: ldarg.1 IL_0043: ldarg.2 IL_0044: ldloca.s V_1 IL_0046: call ""string int.ToString()"" IL_004b: newobj ""System.ValueTuple<string, bool, bool, string>..ctor(string, bool, bool, string)"" IL_0050: box ""System.ValueTuple<string, bool, bool, string>"" IL_0055: call ""void System.Console.WriteLine(object)"" // sequence point: break; IL_005a: ret // sequence point: throw null; IL_005b: ldnull IL_005c: throw // sequence point: throw null; IL_005d: ldnull IL_005e: throw } ", source: source, sequencePoints: "C.M"); } [Fact, WorkItem(55668, "https://github.com/dotnet/roslyn/issues/55668")] public void SharedWhenExpression_Multiples() { // The `b3` condition ends up in the `when` clause on four leaves in the DAG // and `b1` ends up in two leaves var source = @" int count = 0; foreach (int i1 in new[] { 0, 1 }) foreach (int i2 in new[] { 0, 1 }) foreach (int i3 in new[] { 0, 1 }) foreach (bool b0 in new[] { false, true }) foreach (bool b1 in new[] { false, true }) foreach (bool b2 in new[] { false, true }) foreach (bool b3 in new[] { false, true }) { count++; if (M(i1, i2, i3, b0, b1, b2, b3) != M2(i1, i2, i3, b0, b1, b2, b3)) throw null; } System.Console.Write(count); static string M(int i1, int i2, int i3, bool b0, bool b1, bool b2, bool b3) { object o = null; switch (i1, i2, i3) { case (var x, var y, var z) when f(x, y, z): throw null; case (not 0, 0, _) when b0: return ""b0""; case (_, not 0, 0) when b1: return ""b1""; case (0, _, not 0) when b2: return ""b2""; case (_, _, _) when b3: return ""b3""; case (0, _, _): return ""first""; case (_, 0, _): return ""second""; case (_, _, 0): return ""third""; } return ""last""; } static string M2(int i1, int i2, int i3, bool b0, bool b1, bool b2, bool b3) { if (i1 is not 0 && i2 is 0 && b0) return ""b0""; if (i2 is not 0 && i3 is 0 && b1) return ""b1""; if (i3 is not 0 && i1 is 0 && b2) return ""b2""; if (b3) return ""b3""; if (i1 is 0) return ""first""; if (i2 is 0) return ""second""; if (i3 is 0) return ""third""; return ""last""; } static bool f(int i1, int i2, int i3) => false; "; CompileAndVerify(source, expectedOutput: "128"); } [Fact, WorkItem(55668, "https://github.com/dotnet/roslyn/issues/55668")] public void SharedWhenExpression_Multiples_LabelInSharedWhenExpression() { var source = @" int count = 0; var wrap = new Wrap { value = null }; foreach (int i1 in new[] { 0, 1 }) foreach (int i2 in new[] { 0, 1 }) foreach (int i3 in new[] { 0, 1 }) foreach (bool b0 in new[] { false, true }) foreach (bool b1 in new[] { false, true }) foreach (bool b2 in new[] { false, true }) foreach (bool b3 in new[] { false, true }) { count++; if (M(i1, i2, i3, b0, b1, b2, b3) != M2(i1, i2, i3, b0, b1, b2, b3)) throw null; } System.Console.Write(count); string M(int i1, int i2, int i3, bool b0, bool b1, bool b2, bool b3) { switch (i1, i2, i3) { case (var x, var y, var z) when f(x, y, z): throw null; case (not 0, 0, _) when b0 && wrap is { value: string or string[] }: throw null; case (_, not 0, 0) when b1 && wrap is { value: string or string[] }: throw null; case (0, _, not 0) when b2 && wrap is { value: string or string[] }: throw null; case (_, _, _) when b3: return ""b3""; case (0, _, _): return ""first""; case (_, 0, _): return ""second""; case (_, _, 0): return ""third""; } return ""last""; } static string M2(int i1, int i2, int i3, bool b0, bool b1, bool b2, bool b3) { if (b3) return ""b3""; if (i1 is 0) return ""first""; if (i2 is 0) return ""second""; if (i3 is 0) return ""third""; return ""last""; } static bool f(int i1, int i2, int i3) => false; public class Wrap { public object value; } "; CompileAndVerify(source, expectedOutput: "128"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { [CompilerTrait(CompilerFeature.Patterns)] public class PatternMatchingTests2 : PatternMatchingTestBase { [Fact] public void Patterns2_00() { var source = @" using System; class Program { public static void Main() { Console.WriteLine(1 is int {} x ? x : -1); } } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: @"1"); } [Fact] public void Patterns2_01() { var source = @" using System; class Program { public static void Main() { Point p = new Point(); Check(true, p is Point(3, 4) { Length: 5 } q1 && Check(p, q1)); Check(false, p is Point(1, 4) { Length: 5 }); Check(false, p is Point(3, 1) { Length: 5 }); Check(false, p is Point(3, 4) { Length: 1 }); Check(true, p is (3, 4) { Length: 5 } q2 && Check(p, q2)); Check(false, p is (1, 4) { Length: 5 }); Check(false, p is (3, 1) { Length: 5 }); Check(false, p is (3, 4) { Length: 1 }); } private static bool Check<T>(T expected, T actual) { if (!object.Equals(expected, actual)) throw new Exception($""expected: {expected}; actual: {actual}""); return true; } } public class Point { public void Deconstruct(out int X, out int Y) { X = 3; Y = 4; } public int Length => 5; } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: ""); } [Fact] public void Patterns2_02() { var source = @" using System; class Program { public static void Main() { Point p = new Point(); Check(true, p is Point(3, 4) { Length: 5 } q1 && Check(p, q1)); Check(false, p is Point(1, 4) { Length: 5 }); Check(false, p is Point(3, 1) { Length: 5 }); Check(false, p is Point(3, 4) { Length: 1 }); Check(true, p is (3, 4) { Length: 5 } q2 && Check(p, q2)); Check(false, p is (1, 4) { Length: 5 }); Check(false, p is (3, 1) { Length: 5 }); Check(false, p is (3, 4) { Length: 1 }); } private static bool Check<T>(T expected, T actual) { if (!object.Equals(expected, actual)) throw new Exception($""expected: {expected}; actual: {actual}""); return true; } } public class Point { public int Length => 5; } public static class PointExtensions { public static void Deconstruct(this Point p, out int X, out int Y) { X = 3; Y = 4; } } "; // We use a compilation profile that provides System.Runtime.CompilerServices.ExtensionAttribute needed for this test var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularWithRecursivePatterns); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: ""); } [Fact] public void Patterns2_03() { var source = @" using System; class Program { public static void Main() { var p = (x: 3, y: 4); Check(true, p is (3, 4) q1 && Check(p, q1)); Check(false, p is (1, 4) { x: 3 }); Check(false, p is (3, 1) { y: 4 }); Check(false, p is (3, 4) { x: 1 }); Check(true, p is (3, 4) { x: 3 } q2 && Check(p, q2)); Check(false, p is (1, 4) { x: 3 }); Check(false, p is (3, 1) { x: 3 }); Check(false, p is (3, 4) { x: 1 }); } private static bool Check<T>(T expected, T actual) { if (!object.Equals(expected, actual)) throw new Exception($""expected: {expected}; actual: {actual}""); return true; } }"; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (9,22): error CS8415: An expression of type '(int x, int y)' can never match the provided pattern. // Check(false, p is (1, 4) { x: 3 }); Diagnostic(ErrorCode.ERR_IsPatternImpossible, "p is (1, 4) { x: 3 }").WithArguments("(int x, int y)").WithLocation(9, 22), // (10,22): error CS8415: An expression of type '(int x, int y)' can never match the provided pattern. // Check(false, p is (3, 1) { y: 4 }); Diagnostic(ErrorCode.ERR_IsPatternImpossible, "p is (3, 1) { y: 4 }").WithArguments("(int x, int y)").WithLocation(10, 22), // (11,22): error CS8415: An expression of type '(int x, int y)' can never match the provided pattern. // Check(false, p is (3, 4) { x: 1 }); Diagnostic(ErrorCode.ERR_IsPatternImpossible, "p is (3, 4) { x: 1 }").WithArguments("(int x, int y)").WithLocation(11, 22), // (13,22): error CS8415: An expression of type '(int x, int y)' can never match the provided pattern. // Check(false, p is (1, 4) { x: 3 }); Diagnostic(ErrorCode.ERR_IsPatternImpossible, "p is (1, 4) { x: 3 }").WithArguments("(int x, int y)").WithLocation(13, 22), // (15,22): error CS8415: An expression of type '(int x, int y)' can never match the provided pattern. // Check(false, p is (3, 4) { x: 1 }); Diagnostic(ErrorCode.ERR_IsPatternImpossible, "p is (3, 4) { x: 1 }").WithArguments("(int x, int y)").WithLocation(15, 22) ); } [Fact] public void Patterns2_04b() { var source = @" using System; class Program { public static void Main() { var p = (x: 3, y: 4); Check(true, p is (3, 4) q1 && Check(p, q1)); Check(true, p is (3, 4) { x: 3 } q2 && Check(p, q2)); Check(false, p is (3, 1) { x: 3 }); } private static bool Check<T>(T expected, T actual) { if (!object.Equals(expected, actual)) throw new Exception($""expected: {expected}; actual: {actual}""); return true; } }"; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: ""); } [Fact] public void Patterns2_DiscardPattern_01() { var source = @" using System; class Program { public static void Main() { Point p = new Point(); Check(true, p is Point(_, _) { Length: _ } q1 && Check(p, q1)); Check(false, p is Point(1, _) { Length: _ }); Check(false, p is Point(_, 1) { Length: _ }); Check(false, p is Point(_, _) { Length: 1 }); Check(true, p is (_, _) { Length: _ } q2 && Check(p, q2)); Check(false, p is (1, _) { Length: _ }); Check(false, p is (_, 1) { Length: _ }); Check(false, p is (_, _) { Length: 1 }); } private static bool Check<T>(T expected, T actual) { if (!object.Equals(expected, actual)) throw new Exception($""expected: {expected}; actual: {actual}""); return true; } } public class Point { public void Deconstruct(out int X, out int Y) { X = 3; Y = 4; } public int Length => 5; } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: ""); } [Fact] public void Patterns2_Switch01() { var sourceTemplate = @" class Program {{ public static void Main() {{ var p = (true, false); switch (p) {{ {0} {1} {2} case (_, _): // error - subsumed break; }} }} }}"; void testErrorCase(string s1, string s2, string s3) { var source = string.Format(sourceTemplate, s1, s2, s3); var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (12,18): error CS8120: The switch case is unreachable. It has already been handled by a previous case or it is impossible to match. // case (_, _): // error - subsumed Diagnostic(ErrorCode.ERR_SwitchCaseSubsumed, "(_, _)").WithLocation(12, 18) ); } void testGoodCase(string s1, string s2) { var source = string.Format(sourceTemplate, s1, s2, string.Empty); var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( ); } var c1 = "case (true, _):"; var c2 = "case (false, false):"; var c3 = "case (_, true):"; testErrorCase(c1, c2, c3); testErrorCase(c2, c3, c1); testErrorCase(c3, c1, c2); testErrorCase(c1, c3, c2); testErrorCase(c3, c2, c1); testErrorCase(c2, c1, c3); testGoodCase(c1, c2); testGoodCase(c1, c3); testGoodCase(c2, c3); testGoodCase(c2, c1); testGoodCase(c3, c1); testGoodCase(c3, c2); } [Fact] public void Patterns2_Switch02() { var source = @" class Program { public static void Main() { Point p = new Point(); switch (p) { case Point(3, 4) { Length: 5 }: System.Console.WriteLine(true); break; default: System.Console.WriteLine(false); break; } } } public class Point { public void Deconstruct(out int X, out int Y) { X = 3; Y = 4; } public int Length => 5; } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: "True"); } [Fact] public void DefaultPattern() { var source = @"class Program { public static void Main() { int i = 12; if (i is default) {} // error 1 if (i is (default)) {} // error 2 switch (i) { case default: break; } // error 3 switch (i) { case default when true: break; } // error 4 switch ((1, 2)) { case (1, default): break; } // error 5 if (i is < default) {} // error 6 switch (i) { case < default: break; } // error 7 if (i is < ((default))) {} // error 8 switch (i) { case < ((default)): break; } // error 9 if (i is default!) {} // error 10 if (i is (default!)) {} // error 11 if (i is < ((default)!)) {} // error 12 if (i is default!!) {} // error 13 if (i is (default!!)) {} // error 14 if (i is < ((default)!!)) {} // error 15 // These are not accepted by the parser. See https://github.com/dotnet/roslyn/issues/45387 if (i is (default)!) {} // error 16 if (i is ((default)!)) {} // error 17 } }"; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (6,18): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'. // if (i is default) {} // error 1 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(6, 18), // (7,19): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'. // if (i is (default)) {} // error 2 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(7, 19), // (8,27): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'. // switch (i) { case default: break; } // error 3 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(8, 27), // (9,27): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'. // switch (i) { case default when true: break; } // error 4 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(9, 27), // (10,36): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'. // switch ((1, 2)) { case (1, default): break; } // error 5 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(10, 36), // (12,20): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'. // if (i is < default) {} // error 6 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(12, 20), // (13,29): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'. // switch (i) { case < default: break; } // error 7 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(13, 29), // (14,22): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'. // if (i is < ((default))) {} // error 8 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(14, 22), // (15,31): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'. // switch (i) { case < ((default)): break; } // error 9 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(15, 31), // (17,18): error CS8598: The suppression operator is not allowed in this context // if (i is default!) {} // error 10 Diagnostic(ErrorCode.ERR_IllegalSuppression, "default!").WithLocation(17, 18), // (17,18): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'. // if (i is default!) {} // error 10 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(17, 18), // (18,19): error CS8598: The suppression operator is not allowed in this context // if (i is (default!)) {} // error 11 Diagnostic(ErrorCode.ERR_IllegalSuppression, "default!").WithLocation(18, 19), // (18,19): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'. // if (i is (default!)) {} // error 11 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(18, 19), // (19,21): error CS8598: The suppression operator is not allowed in this context // if (i is < ((default)!)) {} // error 12 Diagnostic(ErrorCode.ERR_IllegalSuppression, "(default)!").WithLocation(19, 21), // (19,22): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'. // if (i is < ((default)!)) {} // error 12 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(19, 22), // (20,18): error CS8598: The suppression operator is not allowed in this context // if (i is default!!) {} // error 13 Diagnostic(ErrorCode.ERR_IllegalSuppression, "default!!").WithLocation(20, 18), // (20,18): error CS8598: The suppression operator is not allowed in this context // if (i is default!!) {} // error 13 Diagnostic(ErrorCode.ERR_IllegalSuppression, "default!").WithLocation(20, 18), // (20,18): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'. // if (i is default!!) {} // error 13 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(20, 18), // (21,19): error CS8598: The suppression operator is not allowed in this context // if (i is (default!!)) {} // error 14 Diagnostic(ErrorCode.ERR_IllegalSuppression, "default!!").WithLocation(21, 19), // (21,19): error CS8598: The suppression operator is not allowed in this context // if (i is (default!!)) {} // error 14 Diagnostic(ErrorCode.ERR_IllegalSuppression, "default!").WithLocation(21, 19), // (21,19): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'. // if (i is (default!!)) {} // error 14 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(21, 19), // (22,21): error CS8598: The suppression operator is not allowed in this context // if (i is < ((default)!!)) {} // error 15 Diagnostic(ErrorCode.ERR_IllegalSuppression, "(default)!!").WithLocation(22, 21), // (22,21): error CS8598: The suppression operator is not allowed in this context // if (i is < ((default)!!)) {} // error 15 Diagnostic(ErrorCode.ERR_IllegalSuppression, "(default)!").WithLocation(22, 21), // (22,22): error CS8715: Duplicate null suppression operator ('!') // if (i is < ((default)!!)) {} // error 15 Diagnostic(ErrorCode.ERR_DuplicateNullSuppression, "default").WithLocation(22, 22), // (22,22): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'. // if (i is < ((default)!!)) {} // error 15 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(22, 22), // (25,19): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'. // if (i is (default)!) {} // error 16 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(25, 19), // (25,27): error CS1026: ) expected // if (i is (default)!) {} // error 16 Diagnostic(ErrorCode.ERR_CloseParenExpected, "!").WithLocation(25, 27), // (25,28): error CS1525: Invalid expression term ')' // if (i is (default)!) {} // error 16 Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(25, 28), // (25,28): error CS1002: ; expected // if (i is (default)!) {} // error 16 Diagnostic(ErrorCode.ERR_SemicolonExpected, ")").WithLocation(25, 28), // (25,28): error CS1513: } expected // if (i is (default)!) {} // error 16 Diagnostic(ErrorCode.ERR_RbraceExpected, ")").WithLocation(25, 28), // (26,18): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'int', with 2 out parameters and a void return type. // if (i is ((default)!)) {} // error 17 Diagnostic(ErrorCode.ERR_MissingDeconstruct, "((default)!)").WithArguments("int", "2").WithLocation(26, 18), // (26,20): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'. // if (i is ((default)!)) {} // error 17 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(26, 20), // (26,28): error CS1003: Syntax error, ',' expected // if (i is ((default)!)) {} // error 17 Diagnostic(ErrorCode.ERR_SyntaxError, "!").WithArguments(",", "!").WithLocation(26, 28), // (26,29): error CS1525: Invalid expression term ')' // if (i is ((default)!)) {} // error 17 Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(26, 29) ); } [Fact] public void SwitchExpression_01() { // test appropriate language version or feature flag var source = @"class Program { public static void Main() { var r = 1 switch { _ => 0, }; } }"; CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularWithoutRecursivePatterns).VerifyDiagnostics( // (5,17): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // var r = 1 switch { _ => 0, }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "1 switch { _ => 0, }").WithArguments("recursive patterns", "8.0").WithLocation(5, 17) ); CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular8).VerifyDiagnostics(); } [Fact] public void SwitchExpression_02() { // test switch expression's governing expression has no type // test switch expression's governing expression has type void var source = @"class Program { public static void Main() { var r1 = (1, null) switch { _ => 0 }; var r2 = System.Console.Write(1) switch { _ => 0 }; } }"; CreatePatternCompilation(source).VerifyDiagnostics( // (5,18): error CS8117: Invalid operand for pattern match; value required, but found '(int, <null>)'. // var r1 = (1, null) switch ( _ => 0 ); Diagnostic(ErrorCode.ERR_BadPatternExpression, "(1, null)").WithArguments("(int, <null>)").WithLocation(5, 18), // (6,18): error CS8117: Invalid operand for pattern match; value required, but found 'void'. // var r2 = System.Console.Write(1) switch ( _ => 0 ); Diagnostic(ErrorCode.ERR_BadPatternExpression, "System.Console.Write(1)").WithArguments("void").WithLocation(6, 18) ); } [Fact] public void SwitchExpression_03() { // test that a ternary expression is not at an appropriate precedence // for the constant expression of a constant pattern in a switch expression arm. var source = @"class Program { public static void Main() { bool b = true; var r1 = b switch { true ? true : true => true, false => false }; var r2 = b switch { (true ? true : true) => true, false => false }; } }"; // This is admittedly poor syntax error recovery (for the line declaring r2), // but this test demonstrates that it is a syntax error. CreatePatternCompilation(source).VerifyDiagnostics( // (6,34): error CS1003: Syntax error, '=>' expected // var r1 = b switch { true ? true : true => true, false => false }; Diagnostic(ErrorCode.ERR_SyntaxError, "?").WithArguments("=>", "?").WithLocation(6, 34), // (6,34): error CS1525: Invalid expression term '?' // var r1 = b switch { true ? true : true => true, false => false }; Diagnostic(ErrorCode.ERR_InvalidExprTerm, "?").WithArguments("?").WithLocation(6, 34), // (6,48): error CS1003: Syntax error, ',' expected // var r1 = b switch { true ? true : true => true, false => false }; Diagnostic(ErrorCode.ERR_SyntaxError, "=>").WithArguments(",", "=>").WithLocation(6, 48), // (6,48): error CS8504: Pattern missing // var r1 = b switch { true ? true : true => true, false => false }; Diagnostic(ErrorCode.ERR_MissingPattern, "=>").WithLocation(6, 48) ); } [Fact] public void SwitchExpression_04() { // test that a ternary expression is permitted as a constant pattern in recursive contexts and the case expression. var source = @"class Program { public static void Main() { var b = (true, false); var r1 = b switch { (true ? true : true, _) => true, _ => false, }; var r2 = b is (true ? true : true, _); switch (b.Item1) { case true ? true : true: break; } } }"; CreatePatternCompilation(source).VerifyDiagnostics( ); } [Fact] public void SwitchExpression_05() { // test throw expression in match arm. var source = @"class Program { public static void Main() { var x = 1 switch { 1 => 1, _ => throw null }; } }"; CreatePatternCompilation(source).VerifyDiagnostics( ); } [Fact] public void EmptySwitchExpression() { var source = @"class Program { public static void Main() { var r = 1 switch { }; } }"; CreatePatternCompilation(source).VerifyDiagnostics( // (5,19): warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '_' is not covered. // var r = 1 switch { }; Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustive, "switch").WithArguments("_").WithLocation(5, 19), // (5,19): error CS8506: No best type was found for the switch expression. // var r = 1 switch { }; Diagnostic(ErrorCode.ERR_SwitchExpressionNoBestType, "switch").WithLocation(5, 19)); } [Fact] public void SwitchExpression_06() { // test common type vs delegate in match expression var source = @"class Program { public static void Main() { var x = 1 switch { 0 => M, 1 => new D(M), 2 => M }; x(); } public static void M() {} public delegate void D(); }"; CreatePatternCompilation(source).VerifyDiagnostics( // (5,19): warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '3' is not covered. // var x = 1 switch { 0 => M, 1 => new D(M), 2 => M }; Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustive, "switch").WithArguments("3").WithLocation(5, 19) ); } [Fact] public void SwitchExpression_07() { // test flow analysis of the switch expression var source = @"class Program { public static void Main() { int q = 1; int u; var x = q switch { 0 => u=0, 1 => u=1, _ => u=2 }; System.Console.WriteLine(u); } }"; CreatePatternCompilation(source).VerifyDiagnostics( ); } [Fact] public void SwitchExpression_08() { // test flow analysis of the switch expression var source = @"class Program { public static void Main() { int q = 1; int u; var x = q switch { 0 => u=0, 1 => 1, _ => u=2 }; System.Console.WriteLine(u); } static int M(int i) => i; }"; CreatePatternCompilation(source).VerifyDiagnostics( // (8,34): error CS0165: Use of unassigned local variable 'u' // System.Console.WriteLine(u); Diagnostic(ErrorCode.ERR_UseDefViolation, "u").WithArguments("u").WithLocation(8, 34) ); } [Fact] public void SwitchExpression_09() { // test flow analysis of the switch expression var source = @"class Program { public static void Main() { int q = 1; int u; var x = q switch { 0 => u=0, 1 => u=M(u), _ => u=2, }; System.Console.WriteLine(u); } static int M(int i) => i; }"; CreatePatternCompilation(source).VerifyDiagnostics( // (7,47): error CS0165: Use of unassigned local variable 'u' // var x = q switch { 0 => u=0, 1 => u=M(u), _ => u=2 }; Diagnostic(ErrorCode.ERR_UseDefViolation, "u").WithArguments("u").WithLocation(7, 47) ); } [Fact] public void SwitchExpression_10() { // test lazily inferring variables in the pattern // test lazily inferring variables in the when clause // test lazily inferring variables in the arrow expression var source = @"class Program { public static void Main() { int a = 1; var b = a switch { var x1 => x1, }; var c = a switch { var x2 when x2 is var x3 => x3 }; var d = a switch { var x4 => x4 is var x5 ? x5 : 1, }; } static int M(int i) => i; }"; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (7,19): warning CS8846: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '_' is not covered. However, a pattern with a 'when' clause might successfully match this value. // var c = a switch { var x2 when x2 is var x3 => x3 }; Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustiveWithWhen, "switch").WithArguments("_").WithLocation(7, 19) ); var names = new[] { "x1", "x2", "x3", "x4", "x5" }; var tree = compilation.SyntaxTrees[0]; foreach (var designation in tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>()) { var model = compilation.GetSemanticModel(tree); var symbol = model.GetDeclaredSymbol(designation); Assert.Equal(SymbolKind.Local, symbol.Kind); Assert.Equal("int", ((ILocalSymbol)symbol).Type.ToDisplayString()); } foreach (var ident in tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>()) { var model = compilation.GetSemanticModel(tree); var typeInfo = model.GetTypeInfo(ident); Assert.Equal("int", typeInfo.Type.ToDisplayString()); } } [Fact] public void ShortDiscardInIsPattern() { // test that we forbid a short discard at the top level of an is-pattern expression var source = @"class Program { public static void Main() { int a = 1; if (a is _) { } } }"; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (6,18): error CS0246: The type or namespace name '_' could not be found (are you missing a using directive or an assembly reference?) // if (a is _) { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "_").WithArguments("_").WithLocation(6, 18) ); } [Fact] public void Patterns2_04() { // Test that a single-element deconstruct pattern is an error if no further elements disambiguate. var source = @" using System; class Program { public static void Main() { var t = new System.ValueTuple<int>(1); if (t is (int x)) { } // error 1 switch (t) { case (_): break; } // error 2 var u = t switch { (int y) => y, _ => 2 }; // error 3 if (t is (int z1) _) { } // ok if (t is (Item1: int z2)) { } // ok if (t is (int z3) { }) { } // ok if (t is ValueTuple<int>(int z4)) { } // ok } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular8); compilation.VerifyDiagnostics( // (8,18): error CS8400: Feature 'parenthesized pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // if (t is (int x)) { } // error 1 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "(int x)").WithArguments("parenthesized pattern", "9.0").WithLocation(8, 18), // (8,19): error CS8121: An expression of type 'ValueTuple<int>' cannot be handled by a pattern of type 'int'. // if (t is (int x)) { } // error 1 Diagnostic(ErrorCode.ERR_PatternWrongType, "int").WithArguments("System.ValueTuple<int>", "int").WithLocation(8, 19), // (9,27): error CS8400: Feature 'parenthesized pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // switch (t) { case (_): break; } // error 2 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "(_)").WithArguments("parenthesized pattern", "9.0").WithLocation(9, 27), // (10,28): error CS8400: Feature 'parenthesized pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // var u = t switch { (int y) => y, _ => 2 }; // error 3 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "(int y)").WithArguments("parenthesized pattern", "9.0").WithLocation(10, 28), // (10,29): error CS8121: An expression of type 'ValueTuple<int>' cannot be handled by a pattern of type 'int'. // var u = t switch { (int y) => y, _ => 2 }; // error 3 Diagnostic(ErrorCode.ERR_PatternWrongType, "int").WithArguments("System.ValueTuple<int>", "int").WithLocation(10, 29) ); } [Fact] public void Patterns2_05() { // Test parsing the var pattern // Test binding the var pattern // Test lowering the var pattern for the is-expression var source = @" using System; class Program { public static void Main() { var t = (1, 2); { Check(true, t is var (x, y) && x == 1 && y == 2); } { Check(false, t is var (x, y) && x == 1 && y == 3); } } private static void Check<T>(T expected, T actual) { if (!object.Equals(expected, actual)) throw new Exception($""Expected: '{expected}', Actual: '{actual}'""); } }"; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: @""); } [Fact] public void Patterns2_06() { // Test that 'var' does not bind to a type var source = @" using System; namespace N { class Program { public static void Main() { var t = (1, 2); { Check(true, t is var (x, y) && x == 1 && y == 2); } // error 1 { Check(false, t is var (x, y) && x == 1 && y == 3); } // error 2 { Check(true, t is var x); } // error 3 } private static void Check<T>(T expected, T actual) { if (!object.Equals(expected, actual)) throw new Exception($""Expected: '{expected}', Actual: '{actual}'""); } } class var { } }"; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (9,21): error CS0029: Cannot implicitly convert type '(int, int)' to 'N.var' // var t = (1, 2); Diagnostic(ErrorCode.ERR_NoImplicitConv, "(1, 2)").WithArguments("(int, int)", "N.var").WithLocation(9, 21), // (10,32): error CS8508: The syntax 'var' for a pattern is not permitted to refer to a type, but 'N.var' is in scope here. // { Check(true, t is var (x, y) && x == 1 && y == 2); } // error 1 Diagnostic(ErrorCode.ERR_VarMayNotBindToType, "var").WithArguments("N.var").WithLocation(10, 32), // (10,36): error CS1061: 'var' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'var' could be found (are you missing a using directive or an assembly reference?) // { Check(true, t is var (x, y) && x == 1 && y == 2); } // error 1 Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "(x, y)").WithArguments("N.var", "Deconstruct").WithLocation(10, 36), // (10,36): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'var', with 2 out parameters and a void return type. // { Check(true, t is var (x, y) && x == 1 && y == 2); } // error 1 Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(x, y)").WithArguments("N.var", "2").WithLocation(10, 36), // (11,33): error CS8508: The syntax 'var' for a pattern is not permitted to refer to a type, but 'N.var' is in scope here. // { Check(false, t is var (x, y) && x == 1 && y == 3); } // error 2 Diagnostic(ErrorCode.ERR_VarMayNotBindToType, "var").WithArguments("N.var").WithLocation(11, 33), // (11,37): error CS1061: 'var' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'var' could be found (are you missing a using directive or an assembly reference?) // { Check(false, t is var (x, y) && x == 1 && y == 3); } // error 2 Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "(x, y)").WithArguments("N.var", "Deconstruct").WithLocation(11, 37), // (11,37): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'var', with 2 out parameters and a void return type. // { Check(false, t is var (x, y) && x == 1 && y == 3); } // error 2 Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(x, y)").WithArguments("N.var", "2").WithLocation(11, 37), // (12,32): error CS8508: The syntax 'var' for a pattern is not permitted to refer to a type, but 'N.var' is in scope here. // { Check(true, t is var x); } // error 3 Diagnostic(ErrorCode.ERR_VarMayNotBindToType, "var").WithArguments("N.var").WithLocation(12, 32) ); } [Fact] public void Patterns2_10() { var source = @" using System; class Program { public static void Main() { Console.Write(M((false, false))); Console.Write(M((false, true))); Console.Write(M((true, false))); Console.Write(M((true, true))); } private static int M((bool, bool) t) { switch (t) { case (false, false): return 0; case (false, _): return 1; case (_, false): return 2; case var _: return 3; } } } namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } } }"; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: @"0123"); } [Fact] public void Patterns2_11() { var source = @" using System; class Program { public static void Main() { Console.Write(M((false, false))); Console.Write(M((false, true))); Console.Write(M((true, false))); Console.Write(M((true, true))); } private static int M((bool, bool) t) { switch (t) { case (false, false): return 0; case (false, _): return 1; case (_, false): return 2; case (true, true): return 3; case var _: return 4; } } } namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } } }"; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (20,18): error CS8120: The switch case is unreachable. It has already been handled by a previous case or it is impossible to match. // case var _: return 4; Diagnostic(ErrorCode.ERR_SwitchCaseSubsumed, "var _").WithLocation(20, 18) ); } [Fact] public void Patterns2_12() { var source = @" using System; class Program { public static void Main() { Console.Write(M((false, false))); Console.Write(M((false, true))); Console.Write(M((true, false))); Console.Write(M((true, true))); } private static int M((bool, bool) t) { return t switch { (false, false) => 0, (false, _) => 1, (_, false) => 2, _ => 3 }; } } namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } } }"; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: @"0123"); } [Fact] public void SwitchArmSubsumed() { var source = @"public class X { public static void Main() { string s = string.Empty; string s2 = s switch { null => null, string t => t, ""foo"" => null }; } }"; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (6,61): error CS8410: The pattern is unreachable. It has already been handled by a previous arm of the switch expression or it is impossible to match. // string s2 = s switch { null => null, string t => t, "foo" => null }; Diagnostic(ErrorCode.ERR_SwitchArmSubsumed, @"""foo""").WithLocation(6, 61) ); } [Fact] public void LongTuples() { var source = @"using System; public class X { public static void Main() { var t = (1, 2, 3, 4, 5, 6, 7, 8, 9); { Console.WriteLine(t is (_, _, _, _, _, _, _, _, var t9) ? t9 : 100); } switch (t) { case (_, _, _, _, _, _, _, _, var t9): Console.WriteLine(t9); break; } Console.WriteLine(t switch { (_, _, _, _, _, _, _, _, var t9) => t9 }); } }"; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: @"9 9 9"); } [Fact] public void TypeCheckInPropertyPattern() { var source = @"using System; class Program2 { public static void Main() { object o = new Frog(1, 2); if (o is Frog(1, 2)) { Console.Write(1); } if (o is Frog { A: 1, B: 2 }) { Console.Write(2); } if (o is Frog(1, 2) { A: 1, B: 2, C: 3 }) { Console.Write(3); } if (o is Frog(9, 2) { A: 1, B: 2, C: 3 }) {} else { Console.Write(4); } if (o is Frog(1, 9) { A: 1, B: 2, C: 3 }) {} else { Console.Write(5); } if (o is Frog(1, 2) { A: 9, B: 2, C: 3 }) {} else { Console.Write(6); } if (o is Frog(1, 2) { A: 1, B: 9, C: 3 }) {} else { Console.Write(7); } if (o is Frog(1, 2) { A: 1, B: 2, C: 9 }) {} else { Console.Write(8); } } } class Frog { public object A, B; public object C => (int)A + (int)B; public Frog(object A, object B) => (this.A, this.B) = (A, B); public void Deconstruct(out object A, out object B) => (A, B) = (this.A, this.B); } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: @"12345678"); } [Fact] public void OvereagerSubsumption() { var source = @"class Program2 { public static int Main() => 0; public static void M(object o) { switch (o) { case (1, 2): break; case string s: break; } } } "; var compilation = CreateCompilationWithMscorlib45(source); // doesn't have ITuple // Two errors below instead of one due to https://github.com/dotnet/roslyn/issues/25533 compilation.VerifyDiagnostics( // (8,18): error CS1061: 'object' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // case (1, 2): Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "(1, 2)").WithArguments("object", "Deconstruct").WithLocation(8, 18), // (8,18): error CS8129: No suitable Deconstruct instance or extension method was found for type 'object', with 2 out parameters and a void return type. // case (1, 2): Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(1, 2)").WithArguments("object", "2").WithLocation(8, 18) ); } [Fact] public void UnderscoreDeclaredAndDiscardPattern_01() { var source = @"class Program0 { static int Main() => 0; private const int _ = 1; bool M1(object o) => o is _; bool M2(object o) => o switch { 1 => true, _ => false }; } class Program1 { class _ {} bool M3(object o) => o is _; bool M4(object o) => o switch { 1 => true, _ => false }; } "; var expected = new[] { // (5,31): error CS0246: The type or namespace name '_' could not be found (are you missing a using directive or an assembly reference?) // bool M1(object o) => o is _; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "_").WithArguments("_").WithLocation(5, 31), // (11,31): warning CS8513: The name '_' refers to the type 'Program1._', not the discard pattern. Use '@_' for the type, or 'var _' to discard. // bool M3(object o) => o is _; Diagnostic(ErrorCode.WRN_IsTypeNamedUnderscore, "_").WithArguments("Program1._").WithLocation(11, 31) }; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics(expected); compilation = CreateCompilation(source, parseOptions: TestOptions.Regular8); compilation.VerifyDiagnostics(expected); expected = new[] { // (5,31): error CS0246: The type or namespace name '_' could not be found (are you missing a using directive or an assembly reference?) // bool M1(object o) => o is _; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "_").WithArguments("_").WithLocation(5, 31), // (6,26): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // bool M2(object o) => o switch { 1 => true, _ => false }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "o switch { 1 => true, _ => false }").WithArguments("recursive patterns", "8.0").WithLocation(6, 26), // (12,26): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // bool M4(object o) => o switch { 1 => true, _ => false }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "o switch { 1 => true, _ => false }").WithArguments("recursive patterns", "8.0").WithLocation(12, 26) }; compilation = CreateCompilation(source, parseOptions: TestOptions.Regular7_3); compilation.VerifyDiagnostics(expected); } [Fact] public void UnderscoreDeclaredAndDiscardPattern_02() { var source = @"class Program0 { static int Main() => 0; private const int _ = 1; } class Program1 : Program0 { bool M2(object o) => o switch { 1 => true, _ => false }; // ok, private member not inherited } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( ); } [Fact] public void UnderscoreDeclaredAndDiscardPattern_03() { var source = @"class Program0 { static int Main() => 0; protected const int _ = 1; } class Program1 : Program0 { bool M2(object o) => o switch { 1 => true, _ => false }; } class Program2 { bool _(object q) => true; bool M2(object o) => o switch { 1 => true, _ => false }; } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( ); } [Fact] public void UnderscoreDeclaredAndDiscardPattern_04() { var source = @"using _ = System.Int32; class Program { static int Main() => 0; bool M2(object o) => o switch { 1 => true, _ => false }; } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (1,1): hidden CS8019: Unnecessary using directive. // using _ = System.Int32; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using _ = System.Int32;").WithLocation(1, 1) ); } [Fact] public void EscapingUnderscoreDeclaredAndDiscardPattern_04() { var source = @"class Program0 { static int Main() => 0; private const int _ = 2; bool M1(object o) => o is @_; int M2(object o) => o switch { 1 => 1, @_ => 2, var _ => 3 }; } class Program1 { class _ {} bool M1(object o) => o is @_; } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( ); } [Fact] public void ErroneousSwitchArmDefiniteAssignment() { // When a switch expression arm is erroneous, ensure that the expression is treated as unreachable (e.g. for definite assignment purposes). var source = @"class Program2 { public static int Main() => 0; public static void M(string s) { int i; int j = s switch { ""frog"" => 1, 0 => i, _ => 2 }; } } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (7,41): error CS0029: Cannot implicitly convert type 'int' to 'string' // int j = s switch { "frog" => 1, 0 => i, _ => 2 }; Diagnostic(ErrorCode.ERR_NoImplicitConv, "0").WithArguments("int", "string").WithLocation(7, 41) ); } [Fact, WorkItem(9154, "https://github.com/dotnet/roslyn/issues/9154")] public void ErroneousIsPatternDefiniteAssignment() { var source = @"class Program2 { public static int Main() => 0; void Dummy(object o) {} void Test5() { Dummy((System.Func<object, object, bool>) ((o1, o2) => o1 is int x5 && o2 is int x5 && x5 > 0)); } } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (8,74): error CS0128: A local variable or function named 'x5' is already defined in this scope // o2 is int x5 && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(8, 74) ); } [Fact] public void ERR_IsPatternImpossible() { var source = @"class Program { public static void Main() { System.Console.WriteLine(""frog"" is string { Length: 4, Length: 5 }); } } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (5,34): error CS8415: An expression of type 'string' can never match the provided pattern. // System.Console.WriteLine("frog" is string { Length: 4, Length: 5 }); Diagnostic(ErrorCode.ERR_IsPatternImpossible, @"""frog"" is string { Length: 4, Length: 5 }").WithArguments("string").WithLocation(5, 34) ); } [Fact] public void WRN_GivenExpressionNeverMatchesPattern01() { var source = @"class Program { public static void Main() { System.Console.WriteLine(3 is 4); } } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (5,34): warning CS8416: The given expression never matches the provided pattern. // System.Console.WriteLine(3 is 4); Diagnostic(ErrorCode.WRN_GivenExpressionNeverMatchesPattern, "3 is 4").WithLocation(5, 34) ); } [Fact] public void WRN_GivenExpressionNeverMatchesPattern02() { var source = @"class Program { public static void Main() { const string s = null; System.Console.WriteLine(s is string { Length: 3 }); } } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (6,34): warning CS8416: The given expression never matches the provided pattern. // System.Console.WriteLine(s is string { Length: 3 }); Diagnostic(ErrorCode.WRN_GivenExpressionNeverMatchesPattern, "s is string { Length: 3 }").WithLocation(6, 34) ); } [Fact] public void DefiniteAssignmentForIsPattern01() { var source = @"class Program { public static void Main() { string s = 300.ToString(); System.Console.WriteLine(s is string { Length: int j }); System.Console.WriteLine(j); } } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (7,34): error CS0165: Use of unassigned local variable 'j' // System.Console.WriteLine(j); Diagnostic(ErrorCode.ERR_UseDefViolation, "j").WithArguments("j").WithLocation(7, 34) ); } [Fact] public void DefiniteAssignmentForIsPattern02() { var source = @"class Program { public static void Main() { const string s = ""300""; System.Console.WriteLine(s is string { Length: int j }); System.Console.WriteLine(j); } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularWithRecursivePatterns); compilation.VerifyDiagnostics(); var expectedOutput = @"True 3"; var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); } [Fact] public void DefiniteAssignmentForIsPattern03() { var source = @"class Program { public static void Main() { int j; const string s = null; if (s is string { Length: 3 }) { System.Console.WriteLine(j); } } } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (7,13): warning CS8416: The given expression never matches the provided pattern. // if (s is string { Length: 3 }) Diagnostic(ErrorCode.WRN_GivenExpressionNeverMatchesPattern, "s is string { Length: 3 }").WithLocation(7, 13) ); } [Fact] public void RefutableConstantPattern01() { var source = @"class Program { public static void Main() { int j; const int N = 3; const int M = 3; if (N is M) { } else { System.Console.WriteLine(j); } } } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (8,13): warning CS8417: The given expression always matches the provided constant. // if (N is M) Diagnostic(ErrorCode.WRN_GivenExpressionAlwaysMatchesConstant, "N is M").WithLocation(8, 13) ); } [Fact, WorkItem(25591, "https://github.com/dotnet/roslyn/issues/25591")] public void TupleSubsumptionError() { var source = @"class Program2 { public static void Main() { M(new Fox()); M(new Cat()); M(new Program2()); } static void M(object o) { switch ((o, 0)) { case (Fox fox, _): System.Console.Write(""Fox ""); break; case (Cat cat, _): System.Console.Write(""Cat""); break; } } } class Fox {} class Cat {} "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: @"Fox Cat"); } [Fact, WorkItem(25934, "https://github.com/dotnet/roslyn/issues/25934")] public void NamesInPositionalPatterns01() { var source = @"class Program { static void Main() { switch (a: 1, b: 2) { case (c: 2, d: 3): // error: c and d not defined break; } } } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (7,19): error CS8416: The name 'c' does not identify tuple element 'Item1'. // case (c: 2, d: 3): // error: c and d not defined Diagnostic(ErrorCode.ERR_TupleElementNameMismatch, "c").WithArguments("c", "Item1").WithLocation(7, 19), // (7,25): error CS8416: The name 'd' does not identify tuple element 'Item2'. // case (c: 2, d: 3): // error: c and d not defined Diagnostic(ErrorCode.ERR_TupleElementNameMismatch, "d").WithArguments("d", "Item2").WithLocation(7, 25) ); } [Fact, WorkItem(25934, "https://github.com/dotnet/roslyn/issues/25934")] public void NamesInPositionalPatterns02() { var source = @"class Program { static void Main() { switch (a: 1, b: 2) { case (a: 2, a: 3): break; } } } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (7,25): error CS8416: The name 'a' does not identify tuple element 'Item2'. // case (a: 2, a: 3): Diagnostic(ErrorCode.ERR_TupleElementNameMismatch, "a").WithArguments("a", "Item2").WithLocation(7, 25) ); } [Fact, WorkItem(25934, "https://github.com/dotnet/roslyn/issues/25934")] public void NamesInPositionalPatterns03() { var source = @"class Program { static void Main() { switch (a: 1, b: 2) { case (a: 2, Item2: 3): System.Console.WriteLine(666); break; case (a: 1, Item2: 2): System.Console.WriteLine(111); break; } } } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: @"111"); } [Fact, WorkItem(25934, "https://github.com/dotnet/roslyn/issues/25934")] public void NamesInPositionalPatterns04() { var source = @"class Program { static void Main() { switch (new T(a: 1, b: 2)) { case (c: 2, d: 3): break; } } } class T { public int A; public int B; public T(int a, int b) => (A, B) = (a, b); public void Deconstruct(out int a, out int b) => (a, b) = (A, B); } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (7,19): error CS8417: The name 'c' does not match the corresponding 'Deconstruct' parameter 'a'. // case (c: 2, d: 3): Diagnostic(ErrorCode.ERR_DeconstructParameterNameMismatch, "c").WithArguments("c", "a").WithLocation(7, 19), // (7,25): error CS8417: The name 'd' does not match the corresponding 'Deconstruct' parameter 'b'. // case (c: 2, d: 3): Diagnostic(ErrorCode.ERR_DeconstructParameterNameMismatch, "d").WithArguments("d", "b").WithLocation(7, 25) ); } [Fact, WorkItem(25934, "https://github.com/dotnet/roslyn/issues/25934")] public void NamesInPositionalPatterns05() { var source = @"class Program { static void Main() { switch (new T(a: 1, b: 2)) { case (c: 2, d: 3): break; } } } class T { public int A; public int B; public T(int a, int b) => (A, B) = (a, b); } static class Extensions { public static void Deconstruct(this T t, out int a, out int b) => (a, b) = (t.A, t.B); } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (7,19): error CS8417: The name 'c' does not match the corresponding 'Deconstruct' parameter 'a'. // case (c: 2, d: 3): Diagnostic(ErrorCode.ERR_DeconstructParameterNameMismatch, "c").WithArguments("c", "a").WithLocation(7, 19), // (7,25): error CS8417: The name 'd' does not match the corresponding 'Deconstruct' parameter 'b'. // case (c: 2, d: 3): Diagnostic(ErrorCode.ERR_DeconstructParameterNameMismatch, "d").WithArguments("d", "b").WithLocation(7, 25) ); } [Fact, WorkItem(25934, "https://github.com/dotnet/roslyn/issues/25934")] public void NamesInPositionalPatterns06() { var source = @"class Program { static void Main() { switch (new T(a: 1, b: 2)) { case (a: 2, a: 3): break; } } } class T { public int A; public int B; public T(int a, int b) => (A, B) = (a, b); public void Deconstruct(out int a, out int b) => (a, b) = (A, B); } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (7,25): error CS8417: The name 'a' does not match the corresponding 'Deconstruct' parameter 'b'. // case (a: 2, a: 3): Diagnostic(ErrorCode.ERR_DeconstructParameterNameMismatch, "a").WithArguments("a", "b").WithLocation(7, 25) ); } [Fact, WorkItem(25934, "https://github.com/dotnet/roslyn/issues/25934")] public void NamesInPositionalPatterns07() { var source = @"class Program { static void Main() { switch (new T(a: 1, b: 2)) { case (a: 2, a: 3): break; } } } class T { public int A; public int B; public T(int a, int b) => (A, B) = (a, b); } static class Extensions { public static void Deconstruct(this T t, out int a, out int b) => (a, b) = (t.A, t.B); } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (7,25): error CS8417: The name 'a' does not match the corresponding 'Deconstruct' parameter 'b'. // case (a: 2, a: 3): Diagnostic(ErrorCode.ERR_DeconstructParameterNameMismatch, "a").WithArguments("a", "b").WithLocation(7, 25) ); } [Fact, WorkItem(25934, "https://github.com/dotnet/roslyn/issues/25934")] public void NamesInPositionalPatterns08() { var source = @"class Program { static void Main() { switch (new T(a: 1, b: 2)) { case (a: 2, b: 3): System.Console.WriteLine(666); break; case (a: 1, b: 2): System.Console.WriteLine(111); break; } } } class T { public int A; public int B; public T(int a, int b) => (A, B) = (a, b); public void Deconstruct(out int a, out int b) => (a, b) = (A, B); } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: @"111"); } [Fact, WorkItem(25934, "https://github.com/dotnet/roslyn/issues/25934")] public void NamesInPositionalPatterns09() { var source = @"class Program { static void Main() { switch (new T(a: 1, b: 2)) { case (a: 2, b: 3): System.Console.WriteLine(666); break; case (a: 1, b: 2): System.Console.WriteLine(111); break; } } } class T { public int A; public int B; public T(int a, int b) => (A, B) = (a, b); } static class Extensions { public static void Deconstruct(this T t, out int a, out int b) => (a, b) = (t.A, t.B); } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: @"111"); } [Fact, WorkItem(25934, "https://github.com/dotnet/roslyn/issues/25934")] public void NamesInPositionalPatterns10() { var source = @"class Program { static void Main() { switch (a: 1, b: 2) { case (Item2: 1, 2): break; } } } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (7,19): error CS8416: The name 'Item2' does not identify tuple element 'Item1'. // case (Item2: 1, 2): Diagnostic(ErrorCode.ERR_TupleElementNameMismatch, "Item2").WithArguments("Item2", "Item1").WithLocation(7, 19) ); } [Fact] public void PropertyPatternMemberMissing01() { var source = @"class Program { static void Main(string[] args) { Blah b = null; if (b is Blah { X: int i }) { } } } class Blah { }"; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (6,25): error CS0117: 'Blah' does not contain a definition for 'X' // if (b is Blah { X: int i }) Diagnostic(ErrorCode.ERR_NoSuchMember, "X").WithArguments("Blah", "X").WithLocation(6, 25) ); } [Fact] public void PropertyPatternMemberMissing02() { var source = @"class Program { static void Main(string[] args) { Blah b = null; if (b is Blah { X: int i }) { } } } class Blah { public int X { set {} } }"; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (6,25): error CS0154: The property or indexer 'Blah.X' cannot be used in this context because it lacks the get accessor // if (b is Blah { X: int i }) Diagnostic(ErrorCode.ERR_PropertyLacksGet, "X:").WithArguments("Blah.X").WithLocation(6, 25) ); } [Fact] public void PropertyPatternMemberMissing03() { var source = @"class Program { static void Main(string[] args) { Blah b = null; switch (b) { case Blah { X: int i }: break; } } } class Blah { }"; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (8,25): error CS0117: 'Blah' does not contain a definition for 'X' // case Blah { X: int i }: Diagnostic(ErrorCode.ERR_NoSuchMember, "X").WithArguments("Blah", "X").WithLocation(8, 25) ); } [Fact] public void PropertyPatternMemberMissing04() { var source = @"class Program { static void Main(string[] args) { Blah b = null; switch (b) { case Blah { X: int i }: break; } } } class Blah { public int X { set {} } }"; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (8,25): error CS0154: The property or indexer 'Blah.X' cannot be used in this context because it lacks the get accessor // case Blah { X: int i }: Diagnostic(ErrorCode.ERR_PropertyLacksGet, "X:").WithArguments("Blah.X").WithLocation(8, 25) ); } [Fact] [WorkItem(24550, "https://github.com/dotnet/roslyn/issues/24550")] [WorkItem(1284, "https://github.com/dotnet/csharplang/issues/1284")] public void ConstantPatternVsUnconstrainedTypeParameter03() { var source = @"class C<T> { internal struct S { } static bool Test(S s) { return s is null; } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics( // (6,21): error CS0037: Cannot convert null to 'C<T>.S' because it is a non-nullable value type // return s is null; Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("C<T>.S").WithLocation(6, 21) ); } [Fact] [WorkItem(24550, "https://github.com/dotnet/roslyn/issues/24550")] [WorkItem(1284, "https://github.com/dotnet/csharplang/issues/1284")] public void ConstantPatternVsUnconstrainedTypeParameter04() { var source = @"class C<T> { static bool Test(C<T> x) { return x is 1; } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics( // (5,21): error CS8121: An expression of type 'C<T>' cannot be handled by a pattern of type 'int'. // return x is 1; Diagnostic(ErrorCode.ERR_PatternWrongType, "1").WithArguments("C<T>", "int").WithLocation(5, 21) ); } [Fact] [WorkItem(20724, "https://github.com/dotnet/roslyn/issues/20724")] public void SpeculateWithNameConflict01() { var source = @"public class Class1 { int i = 1; public override int GetHashCode() => 1; public override bool Equals(object obj) { return obj is global::Class1 @class && this.i == @class.i; } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics( ); var tree = compilation.SyntaxTrees[0]; var model = (CSharpSemanticModel)compilation.GetSemanticModel(tree); var returnStatement = tree.GetRoot().DescendantNodes().OfType<ReturnStatementSyntax>().Single(); Assert.Equal("return obj is global::Class1 @class && this.i == @class.i;", returnStatement.ToString()); var modifiedReturnStatement = (ReturnStatementSyntax)new RemoveAliasQualifiers().Visit(returnStatement); Assert.Equal("return obj is Class1 @class && this.i == @class.i;", modifiedReturnStatement.ToString()); var gotModel = model.TryGetSpeculativeSemanticModel(returnStatement.Location.SourceSpan.Start, modifiedReturnStatement, out var speculativeModel); Assert.True(gotModel); Assert.NotNull(speculativeModel); var typeInfo = speculativeModel.GetTypeInfo(modifiedReturnStatement.Expression); Assert.Equal(SpecialType.System_Boolean, typeInfo.Type.SpecialType); } /// <summary> /// Helper class to remove alias qualifications. /// </summary> class RemoveAliasQualifiers : CSharpSyntaxRewriter { public override SyntaxNode VisitAliasQualifiedName(AliasQualifiedNameSyntax node) { return node.Name; } } [Fact] [WorkItem(20724, "https://github.com/dotnet/roslyn/issues/20724")] public void SpeculateWithNameConflict02() { var source = @"public class Class1 { public override int GetHashCode() => 1; public override bool Equals(object obj) { return obj is global::Class1 @class; } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics( ); var tree = compilation.SyntaxTrees[0]; var model = (CSharpSemanticModel)compilation.GetSemanticModel(tree); var returnStatement = tree.GetRoot().DescendantNodes().OfType<ReturnStatementSyntax>().Single(); Assert.Equal("return obj is global::Class1 @class;", returnStatement.ToString()); var modifiedReturnStatement = (ReturnStatementSyntax)new RemoveAliasQualifiers().Visit(returnStatement); Assert.Equal("return obj is Class1 @class;", modifiedReturnStatement.ToString()); var gotModel = model.TryGetSpeculativeSemanticModel(returnStatement.Location.SourceSpan.Start, modifiedReturnStatement, out var speculativeModel); Assert.True(gotModel); Assert.NotNull(speculativeModel); var typeInfo = speculativeModel.GetTypeInfo(modifiedReturnStatement.Expression); Assert.Equal(SpecialType.System_Boolean, typeInfo.Type.SpecialType); } [Fact] public void WrongArity() { var source = @"class Program { static void Main(string[] args) { Point p = new Point() { X = 3, Y = 4 }; if (p is Point()) { } } } class Point { public int X, Y; public void Deconstruct(out int X, out int Y) => (X, Y) = (this.X, this.Y); } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics( // (6,23): error CS7036: There is no argument given that corresponds to the required formal parameter 'X' of 'Point.Deconstruct(out int, out int)' // if (p is Point()) Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "()").WithArguments("X", "Point.Deconstruct(out int, out int)").WithLocation(6, 23), // (6,23): error CS8129: No suitable Deconstruct instance or extension method was found for type 'Point', with 0 out parameters and a void return type. // if (p is Point()) Diagnostic(ErrorCode.ERR_MissingDeconstruct, "()").WithArguments("Point", "0").WithLocation(6, 23) ); } [Fact] public void GetTypeInfo_01() { var source = @"class Program { static void Main(string[] args) { object o = null; Point p = null; if (o is Point(3, string { Length: 2 })) { } if (p is (_, { })) { } if (p is Point({ }, { }, { })) { } if (p is Point(, { })) { } } } class Point { public object X, Y; public void Deconstruct(out object X, out object Y) => (X, Y) = (this.X, this.Y); public Point(object X, object Y) => (this.X, this.Y) = (X, Y); } "; var expected = new[] { new { Source = "Point(3, string { Length: 2 })", Type = "System.Object", ConvertedType = "Point" }, new { Source = "3", Type = "System.Object", ConvertedType = "System.Int32" }, new { Source = "string { Length: 2 }", Type = "System.Object", ConvertedType = "System.String" }, new { Source = "2", Type = "System.Int32", ConvertedType = "System.Int32" }, new { Source = "(_, { })", Type = "Point", ConvertedType = "Point" }, new { Source = "_", Type = "System.Object", ConvertedType = "System.Object" }, new { Source = "{ }", Type = "System.Object", ConvertedType = "System.Object" }, new { Source = "Point({ }, { }, { })", Type = "Point", ConvertedType = "Point" }, new { Source = "{ }", Type = "?", ConvertedType = "?" }, new { Source = "{ }", Type = "?", ConvertedType = "?" }, new { Source = "{ }", Type = "?", ConvertedType = "?" }, new { Source = "Point(, { })", Type = "Point", ConvertedType = "Point" }, new { Source = "", Type = "System.Object", ConvertedType = "System.Object" }, new { Source = "{ }", Type = "System.Object", ConvertedType = "System.Object" }, }; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics( // (10,24): error CS8504: Pattern missing // if (p is Point(, { })) { } Diagnostic(ErrorCode.ERR_MissingPattern, ",").WithLocation(10, 24), // (9,23): error CS1501: No overload for method 'Deconstruct' takes 3 arguments // if (p is Point({ }, { }, { })) { } Diagnostic(ErrorCode.ERR_BadArgCount, "({ }, { }, { })").WithArguments("Deconstruct", "3").WithLocation(9, 23), // (9,23): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'Point', with 3 out parameters and a void return type. // if (p is Point({ }, { }, { })) { } Diagnostic(ErrorCode.ERR_MissingDeconstruct, "({ }, { }, { })").WithArguments("Point", "3").WithLocation(9, 23) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); int i = 0; foreach (var pat in tree.GetRoot().DescendantNodesAndSelf().OfType<PatternSyntax>()) { var typeInfo = model.GetTypeInfo(pat); var ex = expected[i++]; Assert.Equal(ex.Source, pat.ToString()); Assert.Equal(ex.Type, typeInfo.Type.ToTestDisplayString()); Assert.Equal(ex.ConvertedType, typeInfo.ConvertedType.ToTestDisplayString()); } Assert.Equal(expected.Length, i); } [Fact, WorkItem(26613, "https://github.com/dotnet/roslyn/issues/26613")] public void MissingDeconstruct_01() { var source = @"using System; public class C { public void M() { _ = this is (a: 1); } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics( // (4,21): error CS1061: 'C' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?) // _ = this is (a: 1); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "(a: 1)").WithArguments("C", "Deconstruct").WithLocation(4, 21), // (4,21): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'C', with 1 out parameters and a void return type. // _ = this is (a: 1); Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(a: 1)").WithArguments("C", "1").WithLocation(4, 21) ); } [Fact, WorkItem(26613, "https://github.com/dotnet/roslyn/issues/26613")] public void MissingDeconstruct_02() { var source = @"using System; public class C { public void M() { _ = this is C(a: 1); } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics( // (4,22): error CS1061: 'C' does not contain a definition for 'Deconstruct' and no extension method 'Deconstruct' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?) // _ = this is C(a: 1); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "(a: 1)").WithArguments("C", "Deconstruct").WithLocation(4, 22), // (4,22): error CS8129: No suitable Deconstruct instance or extension method was found for type 'C', with 1 out parameters and a void return type. // _ = this is C(a: 1); Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(a: 1)").WithArguments("C", "1").WithLocation(4, 22) ); } [Fact] public void PatternTypeInfo_01() { var source = @" public class C { void M(T1 t1) { if (t1 is T2 (var t3, t4: T4 t4) { V5 : T6 t5 }) {} } } class T1 { } class T2 : T1 { public T5 V5 = null; public void Deconstruct(out T3 t3, out T4 t4) => throw null; } class T3 { } class T4 { } class T5 { } class T6 : T5 { } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var patterns = tree.GetRoot().DescendantNodesAndSelf().OfType<PatternSyntax>().ToArray(); Assert.Equal(4, patterns.Length); Assert.Equal("T2 (var t3, t4: T4 t4) { V5 : T6 t5 }", patterns[0].ToString()); var ti = model.GetTypeInfo(patterns[0]); Assert.Equal("T1", ti.Type.ToTestDisplayString()); Assert.Equal("T2", ti.ConvertedType.ToTestDisplayString()); Assert.Equal("var t3", patterns[1].ToString()); ti = model.GetTypeInfo(patterns[1]); Assert.Equal("T3", ti.Type.ToTestDisplayString()); Assert.Equal("T3", ti.ConvertedType.ToTestDisplayString()); Assert.Equal("T4 t4", patterns[2].ToString()); ti = model.GetTypeInfo(patterns[2]); Assert.Equal("T4", ti.Type.ToTestDisplayString()); Assert.Equal("T4", ti.ConvertedType.ToTestDisplayString()); Assert.Equal("T6 t5", patterns[3].ToString()); ti = model.GetTypeInfo(patterns[3]); Assert.Equal("T5", ti.Type.ToTestDisplayString()); Assert.Equal("T6", ti.ConvertedType.ToTestDisplayString()); } [Fact] public void PatternTypeInfo_02() { var source = @" public class C { void M(object o) { if (o is Point(3, 4.0)) {} } } class Point { public void Deconstruct(out object o1, out System.IComparable o2) => throw null; } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var patterns = tree.GetRoot().DescendantNodesAndSelf().OfType<PatternSyntax>().ToArray(); Assert.Equal(3, patterns.Length); Assert.Equal("Point(3, 4.0)", patterns[0].ToString()); var ti = model.GetTypeInfo(patterns[0]); Assert.Equal("System.Object", ti.Type.ToTestDisplayString()); Assert.Equal("Point", ti.ConvertedType.ToTestDisplayString()); Assert.Equal("3", patterns[1].ToString()); ti = model.GetTypeInfo(patterns[1]); Assert.Equal("System.Object", ti.Type.ToTestDisplayString()); Assert.Equal("System.Int32", ti.ConvertedType.ToTestDisplayString()); Assert.Equal("4.0", patterns[2].ToString()); ti = model.GetTypeInfo(patterns[2]); Assert.Equal("System.IComparable", ti.Type.ToTestDisplayString()); Assert.Equal("System.Double", ti.ConvertedType.ToTestDisplayString()); } [Fact] public void PatternTypeInfo_03() { var source = @" public class C { void M(object o) { if (o is Point(3, 4.0) { Missing: Xyzzy }) {} if (o is Q7 t) {} } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,18): error CS0246: The type or namespace name 'Point' could not be found (are you missing a using directive or an assembly reference?) // if (o is Point(3, 4.0) { Missing: Xyzzy }) {} Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Point").WithArguments("Point").WithLocation(6, 18), // (6,43): error CS0103: The name 'Xyzzy' does not exist in the current context // if (o is Point(3, 4.0) { Missing: Xyzzy }) {} Diagnostic(ErrorCode.ERR_NameNotInContext, "Xyzzy").WithArguments("Xyzzy").WithLocation(6, 43), // (7,18): error CS0246: The type or namespace name 'Q7' could not be found (are you missing a using directive or an assembly reference?) // if (o is Q7 t) {} Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Q7").WithArguments("Q7").WithLocation(7, 18) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var patterns = tree.GetRoot().DescendantNodesAndSelf().OfType<PatternSyntax>().ToArray(); Assert.Equal(5, patterns.Length); Assert.Equal("Point(3, 4.0) { Missing: Xyzzy }", patterns[0].ToString()); var ti = model.GetTypeInfo(patterns[0]); Assert.Equal("System.Object", ti.Type.ToTestDisplayString()); Assert.Equal("Point", ti.ConvertedType.ToTestDisplayString()); Assert.Equal("3", patterns[1].ToString()); ti = model.GetTypeInfo(patterns[1]); Assert.Equal("?", ti.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Error, ti.Type.TypeKind); Assert.Equal("System.Int32", ti.ConvertedType.ToTestDisplayString()); Assert.Equal("4.0", patterns[2].ToString()); ti = model.GetTypeInfo(patterns[2]); Assert.Equal("?", ti.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Error, ti.Type.TypeKind); Assert.Equal("System.Double", ti.ConvertedType.ToTestDisplayString()); Assert.Equal("Xyzzy", patterns[3].ToString()); ti = model.GetTypeInfo(patterns[3]); Assert.Equal("?", ti.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Error, ti.Type.TypeKind); Assert.Equal("?", ti.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Error, ti.ConvertedType.TypeKind); Assert.Equal("Q7 t", patterns[4].ToString()); ti = model.GetTypeInfo(patterns[4]); Assert.Equal("System.Object", ti.Type.ToTestDisplayString()); Assert.Equal("Q7", ti.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Error, ti.ConvertedType.TypeKind); } [Fact] [WorkItem(34678, "https://github.com/dotnet/roslyn/issues/34678")] public void ConstantPatternVsUnconstrainedTypeParameter05() { var source = @"class C<T> { static bool Test1(T t) { return t is null; // 1 } static bool Test2(C<T> t) { return t is null; // ok } static bool Test3(T t) { return t is 1; // 2 } static bool Test4(T t) { return t is ""frog""; // 3 } }"; CreateCompilation(source, options: TestOptions.ReleaseDll).VerifyDiagnostics(); CreateCompilation(source, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (5,21): error CS8511: An expression of type 'T' cannot be handled by a pattern of type '<null>'. Please use language version '8.0' or greater to match an open type with a constant pattern. // return t is null; // 1 Diagnostic(ErrorCode.ERR_ConstantPatternVsOpenType, "null").WithArguments("T", "<null>", "8.0").WithLocation(5, 21), // (13,21): error CS8511: An expression of type 'T' cannot be handled by a pattern of type 'int'. Please use language version '8.0' or greater to match an open type with a constant pattern. // return t is 1; // 2 Diagnostic(ErrorCode.ERR_ConstantPatternVsOpenType, "1").WithArguments("T", "int", "8.0").WithLocation(13, 21), // (17,21): error CS8511: An expression of type 'T' cannot be handled by a pattern of type 'string'. Please use language version '8.0' or greater to match an open type with a constant pattern. // return t is "frog"; // 3 Diagnostic(ErrorCode.ERR_ConstantPatternVsOpenType, @"""frog""").WithArguments("T", "string", "8.0").WithLocation(17, 21)); } [Fact] [WorkItem(34905, "https://github.com/dotnet/roslyn/issues/34905")] public void ConstantPatternVsUnconstrainedTypeParameter06() { var source = @"public class C<T> { public enum E { V1, V2 } public void M() { switch (default(E)) { case E.V1: break; } } } "; CreateCompilation(source, options: TestOptions.ReleaseDll).VerifyDiagnostics(); CreateCompilation(source, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics(); } [Fact] public void WarnUnmatchedIsRelationalPattern() { var source = @"public class C { public void M() { _ = 1 is < 0; // 1 _ = 1 is < 1; // 2 _ = 1 is < 2; // 3 _ = 1 is <= 0; // 4 _ = 1 is <= 1; // 5 _ = 1 is <= 2; // 6 _ = 1 is > 0; // 7 _ = 1 is > 1; // 8 _ = 1 is > 2; // 9 _ = 1 is >= 0; // 10 _ = 1 is >= 1; // 11 _ = 1 is >= 2; // 12 } } "; CreateCompilation(source, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularWithPatternCombinators).VerifyDiagnostics( // (5,13): warning CS8519: The given expression never matches the provided pattern. // _ = 1 is < 0; // 1 Diagnostic(ErrorCode.WRN_GivenExpressionNeverMatchesPattern, "1 is < 0").WithLocation(5, 13), // (6,13): warning CS8519: The given expression never matches the provided pattern. // _ = 1 is < 1; // 2 Diagnostic(ErrorCode.WRN_GivenExpressionNeverMatchesPattern, "1 is < 1").WithLocation(6, 13), // (7,13): error CS8793: The given expression always matches the provided pattern. // _ = 1 is < 2; // 3 Diagnostic(ErrorCode.WRN_GivenExpressionAlwaysMatchesPattern, "1 is < 2").WithLocation(7, 13), // (8,13): warning CS8519: The given expression never matches the provided pattern. // _ = 1 is <= 0; // 4 Diagnostic(ErrorCode.WRN_GivenExpressionNeverMatchesPattern, "1 is <= 0").WithLocation(8, 13), // (9,13): error CS8793: The given expression always matches the provided pattern. // _ = 1 is <= 1; // 5 Diagnostic(ErrorCode.WRN_GivenExpressionAlwaysMatchesPattern, "1 is <= 1").WithLocation(9, 13), // (10,13): error CS8793: The given expression always matches the provided pattern. // _ = 1 is <= 2; // 6 Diagnostic(ErrorCode.WRN_GivenExpressionAlwaysMatchesPattern, "1 is <= 2").WithLocation(10, 13), // (11,13): error CS8793: The given expression always matches the provided pattern. // _ = 1 is > 0; // 7 Diagnostic(ErrorCode.WRN_GivenExpressionAlwaysMatchesPattern, "1 is > 0").WithLocation(11, 13), // (12,13): warning CS8519: The given expression never matches the provided pattern. // _ = 1 is > 1; // 8 Diagnostic(ErrorCode.WRN_GivenExpressionNeverMatchesPattern, "1 is > 1").WithLocation(12, 13), // (13,13): warning CS8519: The given expression never matches the provided pattern. // _ = 1 is > 2; // 9 Diagnostic(ErrorCode.WRN_GivenExpressionNeverMatchesPattern, "1 is > 2").WithLocation(13, 13), // (14,13): error CS8793: The given expression always matches the provided pattern. // _ = 1 is >= 0; // 10 Diagnostic(ErrorCode.WRN_GivenExpressionAlwaysMatchesPattern, "1 is >= 0").WithLocation(14, 13), // (15,13): error CS8793: The given expression always matches the provided pattern. // _ = 1 is >= 1; // 11 Diagnostic(ErrorCode.WRN_GivenExpressionAlwaysMatchesPattern, "1 is >= 1").WithLocation(15, 13), // (16,13): warning CS8519: The given expression never matches the provided pattern. // _ = 1 is >= 2; // 12 Diagnostic(ErrorCode.WRN_GivenExpressionNeverMatchesPattern, "1 is >= 2").WithLocation(16, 13) ); } [Fact] public void RelationalPatternInSwitchWithConstantControllingExpression() { var source = @"public class C { public void M() { switch (1) { case < 0: break; // 1 case < 1: break; // 2 case < 2: break; case < 3: break; // 3 } } } "; CreateCompilation(source, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularWithPatternCombinators).VerifyDiagnostics( // (7,23): warning CS0162: Unreachable code detected // case < 0: break; // 1 Diagnostic(ErrorCode.WRN_UnreachableCode, "break").WithLocation(7, 23), // (8,23): warning CS0162: Unreachable code detected // case < 1: break; // 2 Diagnostic(ErrorCode.WRN_UnreachableCode, "break").WithLocation(8, 23), // (10,23): warning CS0162: Unreachable code detected // case < 3: break; // 3 Diagnostic(ErrorCode.WRN_UnreachableCode, "break").WithLocation(10, 23) ); } [Fact] public void RelationalPatternInSwitchWithOutOfRangeComparand() { var source = @"public class C { public void M(int i) { switch (i) { case < int.MinValue: break; // 1 case <= int.MinValue: break; case > int.MaxValue: break; // 2 case >= int.MaxValue: break; } } public void M(uint i) { switch (i) { case < 0: break; // 3 case <= 0: break; case > uint.MaxValue: break; // 4 case >= uint.MaxValue: break; } } } "; CreateCompilation(source, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularWithPatternCombinators).VerifyDiagnostics( // (7,18): error CS8120: The switch case is unreachable. It has already been handled by a previous case or it is impossible to match. // case < int.MinValue: break; // 1 Diagnostic(ErrorCode.ERR_SwitchCaseSubsumed, "< int.MinValue").WithLocation(7, 18), // (9,18): error CS8120: The switch case is unreachable. It has already been handled by a previous case or it is impossible to match. // case > int.MaxValue: break; // 2 Diagnostic(ErrorCode.ERR_SwitchCaseSubsumed, "> int.MaxValue").WithLocation(9, 18), // (17,18): error CS8120: The switch case is unreachable. It has already been handled by a previous case or it is impossible to match. // case < 0: break; // 3 Diagnostic(ErrorCode.ERR_SwitchCaseSubsumed, "< 0").WithLocation(17, 18), // (19,18): error CS8120: The switch case is unreachable. It has already been handled by a previous case or it is impossible to match. // case > uint.MaxValue: break; // 4 Diagnostic(ErrorCode.ERR_SwitchCaseSubsumed, "> uint.MaxValue").WithLocation(19, 18) ); } [Fact] public void IsRelationalPatternWithOutOfRangeComparand() { var source = @"public class C { public void M(int i) { _ = i is < int.MinValue; // 1 _ = i is <= int.MinValue; _ = i is > int.MaxValue; // 2 _ = i is >= int.MaxValue; } public void M(uint i) { _ = i is < 0; // 3 _ = i is <= 0; _ = i is > uint.MaxValue; // 4 _ = i is >= uint.MaxValue; } } "; CreateCompilation(source, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularWithPatternCombinators).VerifyDiagnostics( // (5,13): error CS8518: An expression of type 'int' can never match the provided pattern. // _ = i is < int.MinValue; // 1 Diagnostic(ErrorCode.ERR_IsPatternImpossible, "i is < int.MinValue").WithArguments("int").WithLocation(5, 13), // (7,13): error CS8518: An expression of type 'int' can never match the provided pattern. // _ = i is > int.MaxValue; // 2 Diagnostic(ErrorCode.ERR_IsPatternImpossible, "i is > int.MaxValue").WithArguments("int").WithLocation(7, 13), // (12,13): error CS8518: An expression of type 'uint' can never match the provided pattern. // _ = i is < 0; // 3 Diagnostic(ErrorCode.ERR_IsPatternImpossible, "i is < 0").WithArguments("uint").WithLocation(12, 13), // (14,13): error CS8518: An expression of type 'uint' can never match the provided pattern. // _ = i is > uint.MaxValue; // 4 Diagnostic(ErrorCode.ERR_IsPatternImpossible, "i is > uint.MaxValue").WithArguments("uint").WithLocation(14, 13) ); } [Fact] public void IsRelationalPatternWithAlwaysMatchingRange() { var source = @"public class C { public void M(int i) { _ = i is > int.MinValue; _ = i is >= int.MinValue; // 1 _ = i is < int.MaxValue; _ = i is <= int.MaxValue; // 2 } public void M(uint i) { _ = i is > 0; _ = i is >= 0; // 3 _ = i is < uint.MaxValue; _ = i is <= uint.MaxValue; // 4 } } "; CreateCompilation(source, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularWithPatternCombinators).VerifyDiagnostics( // (6,13): warning CS8794: An expression of type 'int' always matches the provided pattern. // _ = i is >= int.MinValue; // 1 Diagnostic(ErrorCode.WRN_IsPatternAlways, "i is >= int.MinValue").WithArguments("int").WithLocation(6, 13), // (8,13): warning CS8794: An expression of type 'int' always matches the provided pattern. // _ = i is <= int.MaxValue; // 2 Diagnostic(ErrorCode.WRN_IsPatternAlways, "i is <= int.MaxValue").WithArguments("int").WithLocation(8, 13), // (13,13): warning CS8794: An expression of type 'uint' always matches the provided pattern. // _ = i is >= 0; // 3 Diagnostic(ErrorCode.WRN_IsPatternAlways, "i is >= 0").WithArguments("uint").WithLocation(13, 13), // (15,13): warning CS8794: An expression of type 'uint' always matches the provided pattern. // _ = i is <= uint.MaxValue; // 4 Diagnostic(ErrorCode.WRN_IsPatternAlways, "i is <= uint.MaxValue").WithArguments("uint").WithLocation(15, 13) ); } [Fact] public void IsImpossiblePatternKinds() { var source = @"public class C { public void M(string s) { _ = s is (System.Delegate); // impossible parenthesized type pattern _ = s is not _; // impossible negated pattern _ = s is ""a"" and ""b""; // impossible conjunctive pattern } } "; CreateCompilation(source, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularWithPatternCombinators).VerifyDiagnostics( // (5,19): error CS8121: An expression of type 'string' cannot be handled by a pattern of type 'Delegate'. // _ = s is (System.Delegate); // impossible parenthesized type pattern Diagnostic(ErrorCode.ERR_PatternWrongType, "System.Delegate").WithArguments("string", "System.Delegate").WithLocation(5, 19), // (6,13): error CS8518: An expression of type 'string' can never match the provided pattern. // _ = s is not _; // impossible negated pattern Diagnostic(ErrorCode.ERR_IsPatternImpossible, "s is not _").WithArguments("string").WithLocation(6, 13), // (7,13): error CS8518: An expression of type 'string' can never match the provided pattern. // _ = s is "a" and "b"; // impossible conjunctive pattern Diagnostic(ErrorCode.ERR_IsPatternImpossible, @"s is ""a"" and ""b""").WithArguments("string").WithLocation(7, 13) ); } [Fact] public void IsNullableReferenceType_01() { var source = @"#nullable enable public class C { public void M1(object o) { var t = o is string? { }; } public void M2(object o) { var t = o is (string? { }); } public void M3(object o) { var t = o is string?; } public void M4(object o) { var t = o is string? _; } public void M5(object o) { var t = o is (string? _); } }"; CreateCompilation(source, parseOptions: TestOptions.RegularWithPatternCombinators).VerifyDiagnostics( // (4,22): error CS8116: It is not legal to use nullable type 'string?' in a pattern; use the underlying type 'string' instead. // var t = o is string? { }; Diagnostic(ErrorCode.ERR_PatternNullableType, "string?").WithArguments("string").WithLocation(4, 22), // (7,23): error CS8116: It is not legal to use nullable type 'string?' in a pattern; use the underlying type 'string' instead. // var t = o is (string? { }); Diagnostic(ErrorCode.ERR_PatternNullableType, "string?").WithArguments("string").WithLocation(7, 23), // (10,22): error CS8650: It is not legal to use nullable reference type 'string?' in an is-type expression; use the underlying type 'string' instead. // var t = o is string?; Diagnostic(ErrorCode.ERR_IsNullableType, "string?").WithArguments("string").WithLocation(10, 22), // (13,30): error CS0103: The name '_' does not exist in the current context // var t = o is string? _; Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(13, 30), // (13,31): error CS1003: Syntax error, ':' expected // var t = o is string? _; Diagnostic(ErrorCode.ERR_SyntaxError, ";").WithArguments(":", ";").WithLocation(13, 31), // (13,31): error CS1525: Invalid expression term ';' // var t = o is string? _; Diagnostic(ErrorCode.ERR_InvalidExprTerm, ";").WithArguments(";").WithLocation(13, 31), // (16,22): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'object', with 2 out parameters and a void return type. // var t = o is (string? _); Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(string? _)").WithArguments("object", "2").WithLocation(16, 22), // (16,29): error CS1003: Syntax error, ',' expected // var t = o is (string? _); Diagnostic(ErrorCode.ERR_SyntaxError, "?").WithArguments(",", "?").WithLocation(16, 29), // (16,31): error CS1003: Syntax error, ',' expected // var t = o is (string? _); Diagnostic(ErrorCode.ERR_SyntaxError, "_").WithArguments(",", "").WithLocation(16, 31) ); } [Fact] public void IsAlwaysPatternKinds() { var source = @"public class C { public void M(string s) { _ = s is (_); // always parenthesized discard pattern _ = s is not System.Delegate; // always negated type pattern _ = s is string or null; // always disjunctive pattern } } "; CreateCompilation(source, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularWithPatternCombinators).VerifyDiagnostics( // (6,22): error CS8121: An expression of type 'string' cannot be handled by a pattern of type 'Delegate'. // _ = s is not System.Delegate; // always negated type pattern Diagnostic(ErrorCode.ERR_PatternWrongType, "System.Delegate").WithArguments("string", "System.Delegate").WithLocation(6, 22), // (7,13): warning CS8794: An expression of type 'string' always matches the provided pattern. // _ = s is string or null; // always disjunctive pattern Diagnostic(ErrorCode.WRN_IsPatternAlways, "s is string or null").WithArguments("string").WithLocation(7, 13) ); } [Fact] public void SemanticModelForSwitchExpression() { var source = @"public class C { void M(int i) { C x0 = i switch // 0 { 0 => new A(), 1 => new B(), _ => throw null, }; _ = i switch // 1 { 0 => new A(), 1 => new B(), _ => throw null, }; D x2 = i switch // 2 { 0 => new A(), 1 => new B(), _ => throw null, }; D x3 = i switch // 3 { 0 => new E(), // 3.1 1 => new F(), // 3.2 _ => throw null, }; C x4 = i switch // 4 { 0 => new A(), 1 => new B(), 2 => new C(), _ => throw null, }; D x5 = i switch // 5 { 0 => new A(), 1 => new B(), 2 => new C(), _ => throw null, }; D x6 = i switch // 6 { 0 => 1, 1 => 2, _ => throw null, }; _ = (C)(i switch // 7 { 0 => new A(), 1 => new B(), _ => throw null, }); _ = (D)(i switch // 8 { 0 => new A(), 1 => new B(), _ => throw null, }); _ = (D)(i switch // 9 { 0 => new E(), // 9.1 1 => new F(), // 9.2 _ => throw null, }); _ = (C)(i switch // 10 { 0 => new A(), 1 => new B(), 2 => new C(), _ => throw null, }); _ = (D)(i switch // 11 { 0 => new A(), 1 => new B(), 2 => new C(), _ => throw null, }); _ = (D)(i switch // 12 { 0 => 1, 1 => 2, _ => throw null, }); } } class A : C { } class B : C { } class D { public static implicit operator D(C c) => throw null; public static implicit operator D(short s) => throw null; } class E { public static implicit operator C(E c) => throw null; } class F { public static implicit operator C(F c) => throw null; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularWithPatternCombinators).VerifyDiagnostics( // (11,15): error CS8506: No best type was found for the switch expression. // _ = i switch // 1 Diagnostic(ErrorCode.ERR_SwitchExpressionNoBestType, "switch").WithLocation(11, 15), // (25,18): error CS0029: Cannot implicitly convert type 'E' to 'D' // 0 => new E(), // 3.1 Diagnostic(ErrorCode.ERR_NoImplicitConv, "new E()").WithArguments("E", "D").WithLocation(25, 18), // (26,18): error CS0029: Cannot implicitly convert type 'F' to 'D' // 1 => new F(), // 3.2 Diagnostic(ErrorCode.ERR_NoImplicitConv, "new F()").WithArguments("F", "D").WithLocation(26, 18), // (63,18): error CS0029: Cannot implicitly convert type 'E' to 'D' // 0 => new E(), // 9.1 Diagnostic(ErrorCode.ERR_NoImplicitConv, "new E()").WithArguments("E", "D").WithLocation(63, 18), // (64,18): error CS0029: Cannot implicitly convert type 'F' to 'D' // 1 => new F(), // 9.2 Diagnostic(ErrorCode.ERR_NoImplicitConv, "new F()").WithArguments("F", "D").WithLocation(64, 18) ); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); void checkType(ExpressionSyntax expr, string expectedNaturalType, string expectedConvertedType, ConversionKind expectedConversionKind) { var typeInfo = model.GetTypeInfo(expr); var conversion = model.GetConversion(expr); Assert.Equal(expectedNaturalType, typeInfo.Type?.ToTestDisplayString()); Assert.Equal(expectedConvertedType, typeInfo.ConvertedType?.ToTestDisplayString()); Assert.Equal(expectedConversionKind, conversion.Kind); } var switches = tree.GetRoot().DescendantNodes().OfType<SwitchExpressionSyntax>().ToArray(); for (int i = 0; i < switches.Length; i++) { var expr = switches[i]; switch (i) { case 0: checkType(expr, null, "C", ConversionKind.SwitchExpression); checkType(expr.Arms[0].Expression, "A", "C", ConversionKind.ImplicitReference); checkType(expr.Arms[1].Expression, "B", "C", ConversionKind.ImplicitReference); checkType(expr.Arms[2].Expression, null, "C", ConversionKind.ImplicitThrow); break; case 1: checkType(expr, "?", "?", ConversionKind.Identity); checkType(expr.Arms[0].Expression, "A", "?", ConversionKind.NoConversion); checkType(expr.Arms[1].Expression, "B", "?", ConversionKind.NoConversion); checkType(expr.Arms[2].Expression, null, "?", ConversionKind.ImplicitThrow); break; case 2: checkType(expr, null, "D", ConversionKind.SwitchExpression); checkType(expr.Arms[0].Expression, "A", "D", ConversionKind.ImplicitUserDefined); checkType(expr.Arms[1].Expression, "B", "D", ConversionKind.ImplicitUserDefined); checkType(expr.Arms[2].Expression, null, "D", ConversionKind.ImplicitThrow); break; case 3: checkType(expr, "?", "D", ConversionKind.NoConversion); checkType(expr.Arms[0].Expression, "E", "?", ConversionKind.NoConversion); checkType(expr.Arms[1].Expression, "F", "?", ConversionKind.NoConversion); checkType(expr.Arms[2].Expression, null, "?", ConversionKind.ImplicitThrow); break; case 4: case 10: checkType(expr, "C", "C", ConversionKind.Identity); checkType(expr.Arms[0].Expression, "A", "C", ConversionKind.ImplicitReference); checkType(expr.Arms[1].Expression, "B", "C", ConversionKind.ImplicitReference); checkType(expr.Arms[2].Expression, "C", "C", ConversionKind.Identity); checkType(expr.Arms[3].Expression, null, "C", ConversionKind.ImplicitThrow); break; case 5: checkType(expr, "C", "D", ConversionKind.ImplicitUserDefined); checkType(expr.Arms[0].Expression, "A", "C", ConversionKind.ImplicitReference); checkType(expr.Arms[1].Expression, "B", "C", ConversionKind.ImplicitReference); checkType(expr.Arms[2].Expression, "C", "C", ConversionKind.Identity); checkType(expr.Arms[3].Expression, null, "C", ConversionKind.ImplicitThrow); break; case 11: checkType(expr, "C", "C", ConversionKind.Identity); checkType(expr.Arms[0].Expression, "A", "C", ConversionKind.ImplicitReference); checkType(expr.Arms[1].Expression, "B", "C", ConversionKind.ImplicitReference); checkType(expr.Arms[2].Expression, "C", "C", ConversionKind.Identity); checkType(expr.Arms[3].Expression, null, "C", ConversionKind.ImplicitThrow); break; case 6: checkType(expr, "System.Int32", "D", ConversionKind.SwitchExpression); checkType(expr.Arms[0].Expression, "System.Int32", "D", ConversionKind.ImplicitUserDefined); checkType(expr.Arms[1].Expression, "System.Int32", "D", ConversionKind.ImplicitUserDefined); checkType(expr.Arms[2].Expression, null, "D", ConversionKind.ImplicitThrow); break; case 7: checkType(expr, null, null, ConversionKind.Identity); checkType(expr.Arms[0].Expression, "A", "C", ConversionKind.ImplicitReference); checkType(expr.Arms[1].Expression, "B", "C", ConversionKind.ImplicitReference); checkType(expr.Arms[2].Expression, null, "C", ConversionKind.ImplicitThrow); checkType((CastExpressionSyntax)expr.Parent.Parent, "C", "C", ConversionKind.Identity); break; case 8: checkType(expr, null, null, ConversionKind.Identity); checkType(expr.Arms[0].Expression, "A", "D", ConversionKind.ImplicitUserDefined); checkType(expr.Arms[1].Expression, "B", "D", ConversionKind.ImplicitUserDefined); checkType(expr.Arms[2].Expression, null, "D", ConversionKind.ImplicitThrow); checkType((CastExpressionSyntax)expr.Parent.Parent, "D", "D", ConversionKind.Identity); break; case 9: checkType(expr, "?", "?", ConversionKind.Identity); checkType(expr.Arms[0].Expression, "E", "?", ConversionKind.NoConversion); checkType(expr.Arms[1].Expression, "F", "?", ConversionKind.NoConversion); checkType(expr.Arms[2].Expression, null, "?", ConversionKind.ImplicitThrow); checkType((CastExpressionSyntax)expr.Parent.Parent, "D", "D", ConversionKind.Identity); break; case 12: checkType(expr, "System.Int32", "System.Int32", ConversionKind.Identity); checkType(expr.Arms[0].Expression, "System.Int32", "D", ConversionKind.ImplicitUserDefined); checkType(expr.Arms[1].Expression, "System.Int32", "D", ConversionKind.ImplicitUserDefined); checkType(expr.Arms[2].Expression, null, "D", ConversionKind.ImplicitThrow); checkType((CastExpressionSyntax)expr.Parent.Parent, "D", "D", ConversionKind.Identity); break; default: Assert.False(true); break; } } } [Fact, WorkItem(45946, "https://github.com/dotnet/roslyn/issues/45946")] public void VoidPattern_01() { var source = @" class C { void F(object o) { _ = is this.F(1); } }"; CreateCompilation(source).VerifyDiagnostics( // (6,13): error CS1525: Invalid expression term 'is' // _ = is this.F(1); Diagnostic(ErrorCode.ERR_InvalidExprTerm, "is").WithArguments("is").WithLocation(6, 13) ); } [Fact, WorkItem(45946, "https://github.com/dotnet/roslyn/issues/45946")] public void VoidPattern_02() { var source = @" class C { void F(object o) { _ = switch { this.F(1) => 1 }; } }"; CreateCompilation(source).VerifyDiagnostics( // (6,13): error CS1525: Invalid expression term 'switch' // _ = switch { this.F(1) => 1 }; Diagnostic(ErrorCode.ERR_InvalidExprTerm, "switch").WithArguments("switch").WithLocation(6, 13), // (6,13): warning CS8848: Operator 'switch' cannot be used here due to precedence. Use parentheses to disambiguate. // _ = switch { this.F(1) => 1 }; Diagnostic(ErrorCode.WRN_PrecedenceInversion, "switch").WithArguments("switch").WithLocation(6, 13) ); } [Fact, WorkItem(48112, "https://github.com/dotnet/roslyn/issues/48112")] public void NullableTypePattern() { var source = @" class C { void F(object o) { _ = o switch { (int?) => 1, _ => 0 }; _ = o switch { int? => 1, _ => 0 }; } }"; CreateCompilation(source).VerifyDiagnostics( // (6,25): error CS8116: It is not legal to use nullable type 'int?' in a pattern; use the underlying type 'int' instead. // _ = o switch { (int?) => 1, _ => 0 }; Diagnostic(ErrorCode.ERR_PatternNullableType, "int?").WithArguments("int").WithLocation(6, 25), // (7,24): error CS8116: It is not legal to use nullable type 'int?' in a pattern; use the underlying type 'int' instead. // _ = o switch { int? => 1, _ => 0 }; Diagnostic(ErrorCode.ERR_PatternNullableType, "int?").WithArguments("int").WithLocation(7, 24) ); } [Fact, WorkItem(55668, "https://github.com/dotnet/roslyn/issues/55668")] public void SharedWhenExpression_SwitchExpression() { var source = @" int count = 0; foreach (var position in new[] { Position.First, Position.Last }) { foreach (var wrap in new[] { new Wrap { Sub = new Zero() }, new Wrap { Sub = new One() }, new Wrap { Sub = new Two() }, new Wrap { Sub = new object() } }) { count++; if (M(position, wrap) != M2(position, wrap)) throw null; } } System.Console.Write(count); static string M(Position position, Wrap wrap) { return position switch { not Position.First when wrap.Sub is Zero => ""Not First and Zero"", _ when wrap is { Sub: One or Two } => ""One or Two"", Position.First => ""First"", _ => ""Other"" }; } static string M2(Position position, Wrap wrap) { if (position is not Position.First && wrap.Sub is Zero) return ""Not First and Zero""; if (wrap is { Sub: One or Two }) return ""One or Two""; if (position is Position.First) return ""First""; return ""Other""; } enum Position { First, Last, } class Zero { } class One { } class Two { } class Wrap { public object Sub; } "; CompileAndVerify(source, expectedOutput: "8"); } [Fact, WorkItem(55668, "https://github.com/dotnet/roslyn/issues/55668")] public void SharedWhenExpression_SwitchStatement() { var source = @" M(Position.Last, new Wrap { Sub = new Zero() }); M(Position.Last, new Wrap { Sub = new One() }); M(Position.Last, new Wrap { Sub = new Two() }); M(Position.First, new Wrap { Sub = new Zero() }); M(Position.Last, new Wrap { Sub = new object() }); static void M(Position position, Wrap wrap) { string text; switch (position) { case not Position.First when wrap.Sub is Zero: text = ""Not First and Zero""; break; case var _ when wrap is { Sub: One or Two }: text = ""One or Two""; break; case Position.First: text = ""First""; break; default: text = ""Other""; break; } System.Console.WriteLine((position, wrap.Sub, text)); } enum Position { First, Last, } class Zero { } class One { } class Two { } class Wrap { public object Sub; } "; CompileAndVerify(source, expectedOutput: @" (Last, Zero, Not First and Zero) (Last, One, One or Two) (Last, Two, One or Two) (First, Zero, First) (Last, System.Object, Other)"); } [Fact, WorkItem(55668, "https://github.com/dotnet/roslyn/issues/55668")] public void SharedWhenExpression_SequencePoints() { var source = @" C.M(0, false, false); C.M(0, true, false); C.M(0, false, true); C.M(1, false, false); C.M(1, false, true); C.M(2, false, false); public class C { public static void M(int i, bool b1, bool b2) { string text; switch (i) { case not 1 when b1: text = ""b1""; break; case var _ when b2: text = ""b2""; break; case 1: text = ""1""; break; default: text = ""default""; break; } System.Console.WriteLine((i, b1, b2, text)); } } "; var verifier = CompileAndVerify(source, expectedOutput: @" (0, False, False, default) (0, True, False, b1) (0, False, True, b2) (1, False, False, 1) (1, False, True, b2) (2, False, False, default) "); verifier.VerifyIL("C.M", @" { // Code size 73 (0x49) .maxstack 4 .locals init (string V_0, //text int V_1) // sequence point: switch (i) IL_0000: ldarg.0 // sequence point: <hidden> IL_0001: ldc.i4.1 IL_0002: beq.s IL_000f // sequence point: when b1 IL_0004: ldarg.1 IL_0005: brfalse.s IL_0013 // sequence point: text = ""b1""; IL_0007: ldstr ""b1"" IL_000c: stloc.0 // sequence point: break; IL_000d: br.s IL_0035 // sequence point: <hidden> IL_000f: ldc.i4.0 IL_0010: stloc.1 IL_0011: br.s IL_0015 IL_0013: ldc.i4.2 IL_0014: stloc.1 // sequence point: when b2 IL_0015: ldarg.2 IL_0016: brtrue.s IL_001f // sequence point: <hidden> IL_0018: ldloc.1 IL_0019: brfalse.s IL_0027 IL_001b: ldloc.1 IL_001c: ldc.i4.2 IL_001d: beq.s IL_002f // sequence point: text = ""b2""; IL_001f: ldstr ""b2"" IL_0024: stloc.0 // sequence point: break; IL_0025: br.s IL_0035 // sequence point: text = ""1""; IL_0027: ldstr ""1"" IL_002c: stloc.0 // sequence point: break; IL_002d: br.s IL_0035 // sequence point: text = ""default""; IL_002f: ldstr ""default"" IL_0034: stloc.0 // sequence point: System.Console.WriteLine((i, b1, b2, text)); IL_0035: ldarg.0 IL_0036: ldarg.1 IL_0037: ldarg.2 IL_0038: ldloc.0 IL_0039: newobj ""System.ValueTuple<int, bool, bool, string>..ctor(int, bool, bool, string)"" IL_003e: box ""System.ValueTuple<int, bool, bool, string>"" IL_0043: call ""void System.Console.WriteLine(object)"" // sequence point: } IL_0048: ret } ", source: source, sequencePoints: "C.M"); } [Fact, WorkItem(55668, "https://github.com/dotnet/roslyn/issues/55668")] public void SharedWhenExpression_MissingInt32Type() { var source = @" class C { static void M(string s, bool b1, bool b2) { switch (s) { case not ""one"" when b1: break; case var _ when b2: break; case ""one"": break; default: break; } } } "; var comp = CreateCompilation(source); comp.MakeTypeMissing(SpecialType.System_Int32); comp.VerifyEmitDiagnostics( // (6,9): error CS0518: Predefined type 'System.Int32' is not defined or imported // switch (s) Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"switch (s) { case not ""one"" when b1: break; case var _ when b2: break; case ""one"": break; default: break; }").WithArguments("System.Int32").WithLocation(6, 9), // (6,9): error CS0518: Predefined type 'System.Int32' is not defined or imported // switch (s) Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"switch (s) { case not ""one"" when b1: break; case var _ when b2: break; case ""one"": break; default: break; }").WithArguments("System.Int32").WithLocation(6, 9), // (8,13): error CS0518: Predefined type 'System.Int32' is not defined or imported // case not "one" when b1: Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"case not ""one"" when b1:").WithArguments("System.Int32").WithLocation(8, 13) ); } [Fact, WorkItem(55668, "https://github.com/dotnet/roslyn/issues/55668")] public void SharedWhenExpression_WithBindings() { var source = @" C.M(""Alice"", false, true); C.M(""Bob"", false, true); public class C { public static void M(string s, bool b1, bool b2) { switch (s) { case not ""x"" when b1: throw null; case { Length: var j and > 2 } when b2: System.Console.WriteLine((s, b1, b2, j.ToString())); break; case ""x"": throw null; default: throw null; } } } "; var verifier = CompileAndVerify(source, expectedOutput: @" (Alice, False, True, 5) (Bob, False, True, 3) "); verifier.VerifyIL("C.M", @" { // Code size 95 (0x5f) .maxstack 4 .locals init (int V_0, int V_1, //j string V_2) // sequence point: switch (s) IL_0000: ldarg.0 IL_0001: stloc.2 // sequence point: <hidden> IL_0002: ldloc.2 IL_0003: ldstr ""x"" IL_0008: call ""bool string.op_Equality(string, string)"" IL_000d: brfalse.s IL_002c IL_000f: ldloc.2 IL_0010: callvirt ""int string.Length.get"" IL_0015: stloc.1 // sequence point: <hidden> IL_0016: ldloc.1 IL_0017: ldc.i4.2 IL_0018: bgt.s IL_0031 IL_001a: br.s IL_005b IL_001c: ldloc.2 IL_001d: brfalse.s IL_005d IL_001f: ldloc.2 IL_0020: callvirt ""int string.Length.get"" IL_0025: stloc.1 // sequence point: <hidden> IL_0026: ldloc.1 IL_0027: ldc.i4.2 IL_0028: bgt.s IL_0035 IL_002a: br.s IL_005d // sequence point: when b1 IL_002c: ldarg.1 IL_002d: brfalse.s IL_001c // sequence point: throw null; IL_002f: ldnull IL_0030: throw // sequence point: <hidden> IL_0031: ldc.i4.0 IL_0032: stloc.0 IL_0033: br.s IL_0037 IL_0035: ldc.i4.2 IL_0036: stloc.0 // sequence point: when b2 IL_0037: ldarg.2 IL_0038: brtrue.s IL_0041 // sequence point: <hidden> IL_003a: ldloc.0 IL_003b: brfalse.s IL_005b IL_003d: ldloc.0 IL_003e: ldc.i4.2 IL_003f: beq.s IL_005d // sequence point: System.Console.WriteLine((s, b1, b2, j.ToString())); IL_0041: ldarg.0 IL_0042: ldarg.1 IL_0043: ldarg.2 IL_0044: ldloca.s V_1 IL_0046: call ""string int.ToString()"" IL_004b: newobj ""System.ValueTuple<string, bool, bool, string>..ctor(string, bool, bool, string)"" IL_0050: box ""System.ValueTuple<string, bool, bool, string>"" IL_0055: call ""void System.Console.WriteLine(object)"" // sequence point: break; IL_005a: ret // sequence point: throw null; IL_005b: ldnull IL_005c: throw // sequence point: throw null; IL_005d: ldnull IL_005e: throw } ", source: source, sequencePoints: "C.M"); } [Fact, WorkItem(55668, "https://github.com/dotnet/roslyn/issues/55668")] public void SharedWhenExpression_Multiples() { // The `b3` condition ends up in the `when` clause on four leaves in the DAG // and `b1` ends up in two leaves var source = @" int count = 0; foreach (int i1 in new[] { 0, 1 }) foreach (int i2 in new[] { 0, 1 }) foreach (int i3 in new[] { 0, 1 }) foreach (bool b0 in new[] { false, true }) foreach (bool b1 in new[] { false, true }) foreach (bool b2 in new[] { false, true }) foreach (bool b3 in new[] { false, true }) { count++; if (M(i1, i2, i3, b0, b1, b2, b3) != M2(i1, i2, i3, b0, b1, b2, b3)) throw null; } System.Console.Write(count); static string M(int i1, int i2, int i3, bool b0, bool b1, bool b2, bool b3) { object o = null; switch (i1, i2, i3) { case (var x, var y, var z) when f(x, y, z): throw null; case (not 0, 0, _) when b0: return ""b0""; case (_, not 0, 0) when b1: return ""b1""; case (0, _, not 0) when b2: return ""b2""; case (_, _, _) when b3: return ""b3""; case (0, _, _): return ""first""; case (_, 0, _): return ""second""; case (_, _, 0): return ""third""; } return ""last""; } static string M2(int i1, int i2, int i3, bool b0, bool b1, bool b2, bool b3) { if (i1 is not 0 && i2 is 0 && b0) return ""b0""; if (i2 is not 0 && i3 is 0 && b1) return ""b1""; if (i3 is not 0 && i1 is 0 && b2) return ""b2""; if (b3) return ""b3""; if (i1 is 0) return ""first""; if (i2 is 0) return ""second""; if (i3 is 0) return ""third""; return ""last""; } static bool f(int i1, int i2, int i3) => false; "; CompileAndVerify(source, expectedOutput: "128"); } [Fact, WorkItem(55668, "https://github.com/dotnet/roslyn/issues/55668")] public void SharedWhenExpression_Multiples_LabelInSharedWhenExpression() { var source = @" int count = 0; var wrap = new Wrap { value = null }; foreach (int i1 in new[] { 0, 1 }) foreach (int i2 in new[] { 0, 1 }) foreach (int i3 in new[] { 0, 1 }) foreach (bool b0 in new[] { false, true }) foreach (bool b1 in new[] { false, true }) foreach (bool b2 in new[] { false, true }) foreach (bool b3 in new[] { false, true }) { count++; if (M(i1, i2, i3, b0, b1, b2, b3) != M2(i1, i2, i3, b0, b1, b2, b3)) throw null; } System.Console.Write(count); string M(int i1, int i2, int i3, bool b0, bool b1, bool b2, bool b3) { switch (i1, i2, i3) { case (var x, var y, var z) when f(x, y, z): throw null; case (not 0, 0, _) when b0 && wrap is { value: string or string[] }: throw null; case (_, not 0, 0) when b1 && wrap is { value: string or string[] }: throw null; case (0, _, not 0) when b2 && wrap is { value: string or string[] }: throw null; case (_, _, _) when b3: return ""b3""; case (0, _, _): return ""first""; case (_, 0, _): return ""second""; case (_, _, 0): return ""third""; } return ""last""; } static string M2(int i1, int i2, int i3, bool b0, bool b1, bool b2, bool b3) { if (b3) return ""b3""; if (i1 is 0) return ""first""; if (i2 is 0) return ""second""; if (i3 is 0) return ""third""; return ""last""; } static bool f(int i1, int i2, int i3) => false; public class Wrap { public object value; } "; CompileAndVerify(source, expectedOutput: "128"); } } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Workspace/Mef/FileExtensionsMetadata.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Host.Mef { /// <summary> /// MEF metadata class used to find exports declared for a specific file extensions. /// </summary> internal class FileExtensionsMetadata { public IEnumerable<string> Extensions { get; } public FileExtensionsMetadata(IDictionary<string, object> data) => this.Extensions = ((IReadOnlyDictionary<string, object>)data).GetEnumerableMetadata<string>("Extensions"); public FileExtensionsMetadata(params string[] extensions) { if (extensions?.Length == 0) { throw new ArgumentException(nameof(extensions)); } this.Extensions = extensions; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Host.Mef { /// <summary> /// MEF metadata class used to find exports declared for a specific file extensions. /// </summary> internal class FileExtensionsMetadata { public IEnumerable<string> Extensions { get; } public FileExtensionsMetadata(IDictionary<string, object> data) => this.Extensions = ((IReadOnlyDictionary<string, object>)data).GetEnumerableMetadata<string>("Extensions"); public FileExtensionsMetadata(params string[] extensions) { if (extensions?.Length == 0) { throw new ArgumentException(nameof(extensions)); } this.Extensions = extensions; } } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/Compilers/Core/Portable/FileSystem/RelativePathResolver.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable #pragma warning disable 436 // The type 'RelativePathResolver' conflicts with imported type using System; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Roslyn.Utilities; using System.IO; namespace Microsoft.CodeAnalysis { internal class RelativePathResolver : IEquatable<RelativePathResolver> { public ImmutableArray<string> SearchPaths { get; } public string BaseDirectory { get; } /// <summary> /// Initializes a new instance of the <see cref="RelativePathResolver"/> class. /// </summary> /// <param name="searchPaths">An ordered set of fully qualified /// paths which are searched when resolving assembly names.</param> /// <param name="baseDirectory">Directory used when resolving relative paths.</param> public RelativePathResolver(ImmutableArray<string> searchPaths, string baseDirectory) { Debug.Assert(searchPaths.All(PathUtilities.IsAbsolute)); Debug.Assert(baseDirectory == null || PathUtilities.GetPathKind(baseDirectory) == PathKind.Absolute); SearchPaths = searchPaths; BaseDirectory = baseDirectory; } public string ResolvePath(string reference, string baseFilePath) { string resolvedPath = FileUtilities.ResolveRelativePath(reference, baseFilePath, BaseDirectory, SearchPaths, FileExists); if (resolvedPath == null) { return null; } return FileUtilities.TryNormalizeAbsolutePath(resolvedPath); } protected virtual bool FileExists(string fullPath) { Debug.Assert(fullPath != null); Debug.Assert(PathUtilities.IsAbsolute(fullPath)); return File.Exists(fullPath); } public RelativePathResolver WithSearchPaths(ImmutableArray<string> searchPaths) => new(searchPaths, BaseDirectory); public RelativePathResolver WithBaseDirectory(string baseDirectory) => new(SearchPaths, baseDirectory); public bool Equals(RelativePathResolver other) => BaseDirectory == other.BaseDirectory && SearchPaths.SequenceEqual(other.SearchPaths); public override int GetHashCode() => Hash.Combine(BaseDirectory, Hash.CombineValues(SearchPaths)); public override bool Equals(object obj) => Equals(obj as RelativePathResolver); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable #pragma warning disable 436 // The type 'RelativePathResolver' conflicts with imported type using System; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Roslyn.Utilities; using System.IO; namespace Microsoft.CodeAnalysis { internal class RelativePathResolver : IEquatable<RelativePathResolver> { public ImmutableArray<string> SearchPaths { get; } public string BaseDirectory { get; } /// <summary> /// Initializes a new instance of the <see cref="RelativePathResolver"/> class. /// </summary> /// <param name="searchPaths">An ordered set of fully qualified /// paths which are searched when resolving assembly names.</param> /// <param name="baseDirectory">Directory used when resolving relative paths.</param> public RelativePathResolver(ImmutableArray<string> searchPaths, string baseDirectory) { Debug.Assert(searchPaths.All(PathUtilities.IsAbsolute)); Debug.Assert(baseDirectory == null || PathUtilities.GetPathKind(baseDirectory) == PathKind.Absolute); SearchPaths = searchPaths; BaseDirectory = baseDirectory; } public string ResolvePath(string reference, string baseFilePath) { string resolvedPath = FileUtilities.ResolveRelativePath(reference, baseFilePath, BaseDirectory, SearchPaths, FileExists); if (resolvedPath == null) { return null; } return FileUtilities.TryNormalizeAbsolutePath(resolvedPath); } protected virtual bool FileExists(string fullPath) { Debug.Assert(fullPath != null); Debug.Assert(PathUtilities.IsAbsolute(fullPath)); return File.Exists(fullPath); } public RelativePathResolver WithSearchPaths(ImmutableArray<string> searchPaths) => new(searchPaths, BaseDirectory); public RelativePathResolver WithBaseDirectory(string baseDirectory) => new(SearchPaths, baseDirectory); public bool Equals(RelativePathResolver other) => BaseDirectory == other.BaseDirectory && SearchPaths.SequenceEqual(other.SearchPaths); public override int GetHashCode() => Hash.Combine(BaseDirectory, Hash.CombineValues(SearchPaths)); public override bool Equals(object obj) => Equals(obj as RelativePathResolver); } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/Analyzers/CSharp/Tests/FileHeaders/FileHeaderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Testing; using Xunit; using VerifyCS = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.CSharpCodeFixVerifier< Microsoft.CodeAnalysis.CSharp.FileHeaders.CSharpFileHeaderDiagnosticAnalyzer, Microsoft.CodeAnalysis.CSharp.FileHeaders.CSharpFileHeaderCodeFixProvider>; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.FileHeaders { public class FileHeaderTests { private const string TestSettings = @" [*.cs] file_header_template = Copyright (c) SomeCorp. All rights reserved.\nLicensed under the ??? license. See LICENSE file in the project root for full license information. "; private const string TestSettingsWithEmptyLines = @" [*.cs] file_header_template = \nCopyright (c) SomeCorp. All rights reserved.\n\nLicensed under the ??? license. See LICENSE file in the project root for full license information.\n "; /// <summary> /// Verifies that the analyzer will not report a diagnostic when the file header is not configured. /// </summary> /// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns> [Theory] [InlineData("")] [InlineData("file_header_template =")] [InlineData("file_header_template = unset")] public async Task TestFileHeaderNotConfiguredAsync(string fileHeaderTemplate) { var testCode = @"namespace N { } "; await new VerifyCS.Test { TestCode = testCode, FixedCode = testCode, EditorConfig = $@" [*] {fileHeaderTemplate} ", }.RunAsync(); } /// <summary> /// Verifies that the analyzer will report a diagnostic when the file is completely missing a header. /// </summary> /// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns> [Fact] public async Task TestNoFileHeaderAsync() { var testCode = @"[||]namespace N { } "; var fixedCode = @"// Copyright (c) SomeCorp. All rights reserved. // Licensed under the ??? license. See LICENSE file in the project root for full license information. namespace N { } "; await new VerifyCS.Test { TestCode = testCode, FixedCode = fixedCode, EditorConfig = TestSettings, }.RunAsync(); } /// <summary> /// Verifies that the analyzer will report a diagnostic when the file is completely missing a header. /// </summary> /// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns> [Fact] public async Task TestNoFileHeaderWithUsingDirectiveAsync() { var testCode = @"[||]using System; namespace N { } "; var fixedCode = @"// Copyright (c) SomeCorp. All rights reserved. // Licensed under the ??? license. See LICENSE file in the project root for full license information. using System; namespace N { } "; await new VerifyCS.Test { TestCode = testCode, FixedCode = fixedCode, EditorConfig = TestSettings, }.RunAsync(); } /// <summary> /// Verifies that the analyzer will report a diagnostic when the file is completely missing a header. /// </summary> /// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns> [Fact] public async Task TestNoFileHeaderWithBlankLineAndUsingDirectiveAsync() { var testCode = @"[||] using System; namespace N { } "; var fixedCode = @"// Copyright (c) SomeCorp. All rights reserved. // Licensed under the ??? license. See LICENSE file in the project root for full license information. using System; namespace N { } "; await new VerifyCS.Test { TestCode = testCode, FixedCode = fixedCode, EditorConfig = TestSettings, }.RunAsync(); } /// <summary> /// Verifies that the analyzer will report a diagnostic when the file is completely missing a header. /// </summary> /// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns> [Fact] public async Task TestNoFileHeaderWithWhitespaceLineAsync() { var testCode = "[||] " + @" using System; namespace N { } "; var fixedCode = @"// Copyright (c) SomeCorp. All rights reserved. // Licensed under the ??? license. See LICENSE file in the project root for full license information. using System; namespace N { } "; await new VerifyCS.Test { TestCode = testCode, FixedCode = fixedCode, EditorConfig = TestSettings, }.RunAsync(); } /// <summary> /// Verifies that the built-in variable <c>fileName</c> works as expected. /// </summary> /// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns> [Fact] public async Task TestFileNameBuiltInVariableAsync() { var editorConfig = @" [*.cs] file_header_template = {fileName} Copyright (c) SomeCorp. All rights reserved.\nLicensed under the ??? license. See LICENSE file in the project root for full license information. "; var testCode = @"[||]namespace N { } "; var fixedCode = @"// Test0.cs Copyright (c) SomeCorp. All rights reserved. // Licensed under the ??? license. See LICENSE file in the project root for full license information. namespace N { } "; await new VerifyCS.Test { TestCode = testCode, FixedCode = fixedCode, EditorConfig = editorConfig, }.RunAsync(); } /// <summary> /// Verifies that a valid file header built using single line comments will not produce a diagnostic message. /// </summary> /// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns> [Fact] public async Task TestValidFileHeaderWithSingleLineCommentsAsync() { var testCode = @"// Copyright (c) SomeCorp. All rights reserved. // Licensed under the ??? license. See LICENSE file in the project root for full license information. namespace Bar { } "; await new VerifyCS.Test { TestCode = testCode, FixedCode = testCode, EditorConfig = TestSettings, }.RunAsync(); } /// <summary> /// Verifies that a valid file header built using multi-line comments will not produce a diagnostic message. /// </summary> /// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns> [Fact] public async Task TestValidFileHeaderWithMultiLineComments1Async() { var testCode = @"/* Copyright (c) SomeCorp. All rights reserved. * Licensed under the ??? license. See LICENSE file in the project root for full license information. */ namespace Bar { } "; await new VerifyCS.Test { TestCode = testCode, FixedCode = testCode, EditorConfig = TestSettings, }.RunAsync(); } /// <summary> /// Verifies that a valid file header built using multi-line comments will not produce a diagnostic message. /// </summary> /// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns> [Fact] public async Task TestValidFileHeaderWithMultiLineComments2Async() { var testCode = @"/* Copyright (c) SomeCorp. All rights reserved. Licensed under the ??? license. See LICENSE file in the project root for full license information. */ namespace Bar { } "; await new VerifyCS.Test { TestCode = testCode, FixedCode = testCode, EditorConfig = TestSettings, }.RunAsync(); } /// <summary> /// Verifies that a valid file header built using unterminated multi-line comments will not produce a diagnostic /// message. /// </summary> /// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns> [Fact] public async Task TestValidFileHeaderWithMultiLineComments3Async() { var testCode = @"/* Copyright (c) SomeCorp. All rights reserved. Licensed under the ??? license. See LICENSE file in the project root for full license information. "; await new VerifyCS.Test { TestCode = testCode, ExpectedDiagnostics = { // /0/Test0.cs(1,1): error CS1035: End-of-file found, '*/' expected DiagnosticResult.CompilerError("CS1035").WithSpan(1, 1, 1, 1), }, FixedCode = testCode, EditorConfig = TestSettings, }.RunAsync(); } /// <summary> /// Verifies that a file header without text / only whitespace will produce the expected diagnostic message. /// </summary> /// <param name="comment">The comment text.</param> /// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns> [Theory] [InlineData("[|//|]")] [InlineData("[|//|] ")] public async Task TestInvalidFileHeaderWithoutTextAsync(string comment) { var testCode = $@"{comment} namespace Bar {{ }} "; var fixedCode = @"// Copyright (c) SomeCorp. All rights reserved. // Licensed under the ??? license. See LICENSE file in the project root for full license information. namespace Bar { } "; await new VerifyCS.Test { TestCode = testCode, FixedCode = fixedCode, EditorConfig = TestSettings, }.RunAsync(); } /// <summary> /// Verifies that an invalid file header built using single line comments will produce the expected diagnostic message. /// </summary> /// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns> [Fact] public async Task TestInvalidFileHeaderWithWrongTextAsync() { var testCode = @"[|//|] Copyright (c) OtherCorp. All rights reserved. // Licensed under the ??? license. See LICENSE file in the project root for full license information. namespace Bar { } "; var fixedCode = @"// Copyright (c) SomeCorp. All rights reserved. // Licensed under the ??? license. See LICENSE file in the project root for full license information. namespace Bar { } "; await new VerifyCS.Test { TestCode = testCode, FixedCode = fixedCode, EditorConfig = TestSettings, }.RunAsync(); } /// <summary> /// Verifies that an invalid file header built using single line comments will produce the expected diagnostic message. /// </summary> /// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns> [Fact] public async Task TestInvalidFileHeaderWithWrongText2Async() { var testCode = @"[|/*|] Copyright (c) OtherCorp. All rights reserved. * Licensed under the ??? license. See LICENSE file in the project root for full license information. */ namespace Bar { } "; var fixedCode = @"// Copyright (c) SomeCorp. All rights reserved. // Licensed under the ??? license. See LICENSE file in the project root for full license information. /* Copyright (c) OtherCorp. All rights reserved. * Licensed under the ??? license. See LICENSE file in the project root for full license information. */ namespace Bar { } "; await new VerifyCS.Test { TestCode = testCode, FixedCode = fixedCode, EditorConfig = TestSettings, }.RunAsync(); } [Theory] [InlineData("", "")] [InlineData(" Header", "")] [InlineData(" Header", " Header")] public async Task TestValidFileHeaderInRegionAsync(string startLabel, string endLabel) { var testCode = $@"#region{startLabel} // Copyright (c) SomeCorp. All rights reserved. // Licensed under the ??? license. See LICENSE file in the project root for full license information. #endregion{endLabel} namespace Bar {{ }} "; await new VerifyCS.Test { TestCode = testCode, FixedCode = testCode, EditorConfig = TestSettings, }.RunAsync(); } [Theory] [InlineData("", "")] [InlineData(" Header", "")] [InlineData(" Header", " Header")] public async Task TestInvalidFileHeaderWithWrongTextInRegionAsync(string startLabel, string endLabel) { var testCode = $@"#region{startLabel} [|//|] Copyright (c) OtherCorp. All rights reserved. // Licensed under the ??? license. See LICENSE file in the project root for full license information. #endregion{endLabel} namespace Bar {{ }} "; var fixedCode = $@"// Copyright (c) SomeCorp. All rights reserved. // Licensed under the ??? license. See LICENSE file in the project root for full license information. #region{startLabel} // Copyright (c) OtherCorp. All rights reserved. // Licensed under the ??? license. See LICENSE file in the project root for full license information. #endregion{endLabel} namespace Bar {{ }} "; await new VerifyCS.Test { TestCode = testCode, FixedCode = fixedCode, EditorConfig = TestSettings, }.RunAsync(); } /// <summary> /// Verifies that an invalid file header built using single line comments will produce the expected diagnostic message. /// </summary> /// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns> [Fact] public async Task TestInvalidFileHeaderWithWrongTextInUnterminatedMultiLineComment1Async() { var testCode = @"{|CS1035:|}[|/*|] Copyright (c) OtherCorp. All rights reserved. * Licensed under the ??? license. See LICENSE file in the project root for full license information. "; var fixedCode = @"// Copyright (c) SomeCorp. All rights reserved. // Licensed under the ??? license. See LICENSE file in the project root for full license information. {|CS1035:|}/* Copyright (c) OtherCorp. All rights reserved. * Licensed under the ??? license. See LICENSE file in the project root for full license information. "; await new VerifyCS.Test { TestCode = testCode, FixedCode = fixedCode, EditorConfig = TestSettings, }.RunAsync(); } /// <summary> /// Verifies that an invalid file header built using single line comments will produce the expected diagnostic message. /// </summary> /// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns> [Fact] public async Task TestInvalidFileHeaderWithWrongTextInUnterminatedMultiLineComment2Async() { var testCode = @"{|CS1035:|}[|/*|]/ "; var fixedCode = @"// Copyright (c) SomeCorp. All rights reserved. // Licensed under the ??? license. See LICENSE file in the project root for full license information. {|CS1035:|}/*/ "; await new VerifyCS.Test { TestCode = testCode, FixedCode = fixedCode, EditorConfig = TestSettings, }.RunAsync(); } /// <summary> /// Verifies that an invalid file header built using single line comments will produce the expected diagnostic message. /// </summary> /// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns> [Theory] [InlineData("")] [InlineData(" ")] public async Task TestInvalidFileHeaderWithWrongTextAfterBlankLineAsync(string firstLine) { var testCode = $@"{firstLine} [|//|] Copyright (c) OtherCorp. All rights reserved. // Licensed under the ??? license. See LICENSE file in the project root for full license information. namespace Bar {{ }} "; var fixedCode = @"// Copyright (c) SomeCorp. All rights reserved. // Licensed under the ??? license. See LICENSE file in the project root for full license information. namespace Bar { } "; await new VerifyCS.Test { TestCode = testCode, FixedCode = fixedCode, EditorConfig = TestSettings, }.RunAsync(); } /// <summary> /// Verifies that an invalid file header built using single line comments will produce the expected diagnostic message. /// </summary> /// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns> [Fact] public async Task TestInvalidFileHeaderWithWrongTextFollowedByCommentAsync() { var testCode = @"[|//|] Copyright (c) OtherCorp. All rights reserved. // Licensed under the ??? license. See LICENSE file in the project root for full license information. //using System; namespace Bar { } "; var fixedCode = @"// Copyright (c) SomeCorp. All rights reserved. // Licensed under the ??? license. See LICENSE file in the project root for full license information. //using System; namespace Bar { } "; await new VerifyCS.Test { TestCode = testCode, FixedCode = fixedCode, EditorConfig = TestSettings, }.RunAsync(); } [Fact] public async Task TestHeaderMissingRequiredNewLinesAsync() { var testCode = @"[|//|] Copyright (c) SomeCorp. All rights reserved. // Licensed under the ??? license. See LICENSE file in the project root for full license information. namespace Bar { } "; var fixedCode = @"// // Copyright (c) SomeCorp. All rights reserved. // // Licensed under the ??? license. See LICENSE file in the project root for full license information. // namespace Bar { } "; await new VerifyCS.Test { TestCode = testCode, FixedCode = fixedCode, EditorConfig = TestSettingsWithEmptyLines, }.RunAsync(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.Testing; using Xunit; using VerifyCS = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.CSharpCodeFixVerifier< Microsoft.CodeAnalysis.CSharp.FileHeaders.CSharpFileHeaderDiagnosticAnalyzer, Microsoft.CodeAnalysis.CSharp.FileHeaders.CSharpFileHeaderCodeFixProvider>; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.FileHeaders { public class FileHeaderTests { private const string TestSettings = @" [*.cs] file_header_template = Copyright (c) SomeCorp. All rights reserved.\nLicensed under the ??? license. See LICENSE file in the project root for full license information. "; private const string TestSettingsWithEmptyLines = @" [*.cs] file_header_template = \nCopyright (c) SomeCorp. All rights reserved.\n\nLicensed under the ??? license. See LICENSE file in the project root for full license information.\n "; /// <summary> /// Verifies that the analyzer will not report a diagnostic when the file header is not configured. /// </summary> /// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns> [Theory] [InlineData("")] [InlineData("file_header_template =")] [InlineData("file_header_template = unset")] public async Task TestFileHeaderNotConfiguredAsync(string fileHeaderTemplate) { var testCode = @"namespace N { } "; await new VerifyCS.Test { TestCode = testCode, FixedCode = testCode, EditorConfig = $@" [*] {fileHeaderTemplate} ", }.RunAsync(); } /// <summary> /// Verifies that the analyzer will report a diagnostic when the file is completely missing a header. /// </summary> /// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns> [Fact] public async Task TestNoFileHeaderAsync() { var testCode = @"[||]namespace N { } "; var fixedCode = @"// Copyright (c) SomeCorp. All rights reserved. // Licensed under the ??? license. See LICENSE file in the project root for full license information. namespace N { } "; await new VerifyCS.Test { TestCode = testCode, FixedCode = fixedCode, EditorConfig = TestSettings, }.RunAsync(); } /// <summary> /// Verifies that the analyzer will report a diagnostic when the file is completely missing a header. /// </summary> /// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns> [Fact] public async Task TestNoFileHeaderWithUsingDirectiveAsync() { var testCode = @"[||]using System; namespace N { } "; var fixedCode = @"// Copyright (c) SomeCorp. All rights reserved. // Licensed under the ??? license. See LICENSE file in the project root for full license information. using System; namespace N { } "; await new VerifyCS.Test { TestCode = testCode, FixedCode = fixedCode, EditorConfig = TestSettings, }.RunAsync(); } /// <summary> /// Verifies that the analyzer will report a diagnostic when the file is completely missing a header. /// </summary> /// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns> [Fact] public async Task TestNoFileHeaderWithBlankLineAndUsingDirectiveAsync() { var testCode = @"[||] using System; namespace N { } "; var fixedCode = @"// Copyright (c) SomeCorp. All rights reserved. // Licensed under the ??? license. See LICENSE file in the project root for full license information. using System; namespace N { } "; await new VerifyCS.Test { TestCode = testCode, FixedCode = fixedCode, EditorConfig = TestSettings, }.RunAsync(); } /// <summary> /// Verifies that the analyzer will report a diagnostic when the file is completely missing a header. /// </summary> /// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns> [Fact] public async Task TestNoFileHeaderWithWhitespaceLineAsync() { var testCode = "[||] " + @" using System; namespace N { } "; var fixedCode = @"// Copyright (c) SomeCorp. All rights reserved. // Licensed under the ??? license. See LICENSE file in the project root for full license information. using System; namespace N { } "; await new VerifyCS.Test { TestCode = testCode, FixedCode = fixedCode, EditorConfig = TestSettings, }.RunAsync(); } /// <summary> /// Verifies that the built-in variable <c>fileName</c> works as expected. /// </summary> /// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns> [Fact] public async Task TestFileNameBuiltInVariableAsync() { var editorConfig = @" [*.cs] file_header_template = {fileName} Copyright (c) SomeCorp. All rights reserved.\nLicensed under the ??? license. See LICENSE file in the project root for full license information. "; var testCode = @"[||]namespace N { } "; var fixedCode = @"// Test0.cs Copyright (c) SomeCorp. All rights reserved. // Licensed under the ??? license. See LICENSE file in the project root for full license information. namespace N { } "; await new VerifyCS.Test { TestCode = testCode, FixedCode = fixedCode, EditorConfig = editorConfig, }.RunAsync(); } /// <summary> /// Verifies that a valid file header built using single line comments will not produce a diagnostic message. /// </summary> /// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns> [Fact] public async Task TestValidFileHeaderWithSingleLineCommentsAsync() { var testCode = @"// Copyright (c) SomeCorp. All rights reserved. // Licensed under the ??? license. See LICENSE file in the project root for full license information. namespace Bar { } "; await new VerifyCS.Test { TestCode = testCode, FixedCode = testCode, EditorConfig = TestSettings, }.RunAsync(); } /// <summary> /// Verifies that a valid file header built using multi-line comments will not produce a diagnostic message. /// </summary> /// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns> [Fact] public async Task TestValidFileHeaderWithMultiLineComments1Async() { var testCode = @"/* Copyright (c) SomeCorp. All rights reserved. * Licensed under the ??? license. See LICENSE file in the project root for full license information. */ namespace Bar { } "; await new VerifyCS.Test { TestCode = testCode, FixedCode = testCode, EditorConfig = TestSettings, }.RunAsync(); } /// <summary> /// Verifies that a valid file header built using multi-line comments will not produce a diagnostic message. /// </summary> /// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns> [Fact] public async Task TestValidFileHeaderWithMultiLineComments2Async() { var testCode = @"/* Copyright (c) SomeCorp. All rights reserved. Licensed under the ??? license. See LICENSE file in the project root for full license information. */ namespace Bar { } "; await new VerifyCS.Test { TestCode = testCode, FixedCode = testCode, EditorConfig = TestSettings, }.RunAsync(); } /// <summary> /// Verifies that a valid file header built using unterminated multi-line comments will not produce a diagnostic /// message. /// </summary> /// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns> [Fact] public async Task TestValidFileHeaderWithMultiLineComments3Async() { var testCode = @"/* Copyright (c) SomeCorp. All rights reserved. Licensed under the ??? license. See LICENSE file in the project root for full license information. "; await new VerifyCS.Test { TestCode = testCode, ExpectedDiagnostics = { // /0/Test0.cs(1,1): error CS1035: End-of-file found, '*/' expected DiagnosticResult.CompilerError("CS1035").WithSpan(1, 1, 1, 1), }, FixedCode = testCode, EditorConfig = TestSettings, }.RunAsync(); } /// <summary> /// Verifies that a file header without text / only whitespace will produce the expected diagnostic message. /// </summary> /// <param name="comment">The comment text.</param> /// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns> [Theory] [InlineData("[|//|]")] [InlineData("[|//|] ")] public async Task TestInvalidFileHeaderWithoutTextAsync(string comment) { var testCode = $@"{comment} namespace Bar {{ }} "; var fixedCode = @"// Copyright (c) SomeCorp. All rights reserved. // Licensed under the ??? license. See LICENSE file in the project root for full license information. namespace Bar { } "; await new VerifyCS.Test { TestCode = testCode, FixedCode = fixedCode, EditorConfig = TestSettings, }.RunAsync(); } /// <summary> /// Verifies that an invalid file header built using single line comments will produce the expected diagnostic message. /// </summary> /// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns> [Fact] public async Task TestInvalidFileHeaderWithWrongTextAsync() { var testCode = @"[|//|] Copyright (c) OtherCorp. All rights reserved. // Licensed under the ??? license. See LICENSE file in the project root for full license information. namespace Bar { } "; var fixedCode = @"// Copyright (c) SomeCorp. All rights reserved. // Licensed under the ??? license. See LICENSE file in the project root for full license information. namespace Bar { } "; await new VerifyCS.Test { TestCode = testCode, FixedCode = fixedCode, EditorConfig = TestSettings, }.RunAsync(); } /// <summary> /// Verifies that an invalid file header built using single line comments will produce the expected diagnostic message. /// </summary> /// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns> [Fact] public async Task TestInvalidFileHeaderWithWrongText2Async() { var testCode = @"[|/*|] Copyright (c) OtherCorp. All rights reserved. * Licensed under the ??? license. See LICENSE file in the project root for full license information. */ namespace Bar { } "; var fixedCode = @"// Copyright (c) SomeCorp. All rights reserved. // Licensed under the ??? license. See LICENSE file in the project root for full license information. /* Copyright (c) OtherCorp. All rights reserved. * Licensed under the ??? license. See LICENSE file in the project root for full license information. */ namespace Bar { } "; await new VerifyCS.Test { TestCode = testCode, FixedCode = fixedCode, EditorConfig = TestSettings, }.RunAsync(); } [Theory] [InlineData("", "")] [InlineData(" Header", "")] [InlineData(" Header", " Header")] public async Task TestValidFileHeaderInRegionAsync(string startLabel, string endLabel) { var testCode = $@"#region{startLabel} // Copyright (c) SomeCorp. All rights reserved. // Licensed under the ??? license. See LICENSE file in the project root for full license information. #endregion{endLabel} namespace Bar {{ }} "; await new VerifyCS.Test { TestCode = testCode, FixedCode = testCode, EditorConfig = TestSettings, }.RunAsync(); } [Theory] [InlineData("", "")] [InlineData(" Header", "")] [InlineData(" Header", " Header")] public async Task TestInvalidFileHeaderWithWrongTextInRegionAsync(string startLabel, string endLabel) { var testCode = $@"#region{startLabel} [|//|] Copyright (c) OtherCorp. All rights reserved. // Licensed under the ??? license. See LICENSE file in the project root for full license information. #endregion{endLabel} namespace Bar {{ }} "; var fixedCode = $@"// Copyright (c) SomeCorp. All rights reserved. // Licensed under the ??? license. See LICENSE file in the project root for full license information. #region{startLabel} // Copyright (c) OtherCorp. All rights reserved. // Licensed under the ??? license. See LICENSE file in the project root for full license information. #endregion{endLabel} namespace Bar {{ }} "; await new VerifyCS.Test { TestCode = testCode, FixedCode = fixedCode, EditorConfig = TestSettings, }.RunAsync(); } /// <summary> /// Verifies that an invalid file header built using single line comments will produce the expected diagnostic message. /// </summary> /// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns> [Fact] public async Task TestInvalidFileHeaderWithWrongTextInUnterminatedMultiLineComment1Async() { var testCode = @"{|CS1035:|}[|/*|] Copyright (c) OtherCorp. All rights reserved. * Licensed under the ??? license. See LICENSE file in the project root for full license information. "; var fixedCode = @"// Copyright (c) SomeCorp. All rights reserved. // Licensed under the ??? license. See LICENSE file in the project root for full license information. {|CS1035:|}/* Copyright (c) OtherCorp. All rights reserved. * Licensed under the ??? license. See LICENSE file in the project root for full license information. "; await new VerifyCS.Test { TestCode = testCode, FixedCode = fixedCode, EditorConfig = TestSettings, }.RunAsync(); } /// <summary> /// Verifies that an invalid file header built using single line comments will produce the expected diagnostic message. /// </summary> /// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns> [Fact] public async Task TestInvalidFileHeaderWithWrongTextInUnterminatedMultiLineComment2Async() { var testCode = @"{|CS1035:|}[|/*|]/ "; var fixedCode = @"// Copyright (c) SomeCorp. All rights reserved. // Licensed under the ??? license. See LICENSE file in the project root for full license information. {|CS1035:|}/*/ "; await new VerifyCS.Test { TestCode = testCode, FixedCode = fixedCode, EditorConfig = TestSettings, }.RunAsync(); } /// <summary> /// Verifies that an invalid file header built using single line comments will produce the expected diagnostic message. /// </summary> /// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns> [Theory] [InlineData("")] [InlineData(" ")] public async Task TestInvalidFileHeaderWithWrongTextAfterBlankLineAsync(string firstLine) { var testCode = $@"{firstLine} [|//|] Copyright (c) OtherCorp. All rights reserved. // Licensed under the ??? license. See LICENSE file in the project root for full license information. namespace Bar {{ }} "; var fixedCode = @"// Copyright (c) SomeCorp. All rights reserved. // Licensed under the ??? license. See LICENSE file in the project root for full license information. namespace Bar { } "; await new VerifyCS.Test { TestCode = testCode, FixedCode = fixedCode, EditorConfig = TestSettings, }.RunAsync(); } /// <summary> /// Verifies that an invalid file header built using single line comments will produce the expected diagnostic message. /// </summary> /// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns> [Fact] public async Task TestInvalidFileHeaderWithWrongTextFollowedByCommentAsync() { var testCode = @"[|//|] Copyright (c) OtherCorp. All rights reserved. // Licensed under the ??? license. See LICENSE file in the project root for full license information. //using System; namespace Bar { } "; var fixedCode = @"// Copyright (c) SomeCorp. All rights reserved. // Licensed under the ??? license. See LICENSE file in the project root for full license information. //using System; namespace Bar { } "; await new VerifyCS.Test { TestCode = testCode, FixedCode = fixedCode, EditorConfig = TestSettings, }.RunAsync(); } [Fact] public async Task TestHeaderMissingRequiredNewLinesAsync() { var testCode = @"[|//|] Copyright (c) SomeCorp. All rights reserved. // Licensed under the ??? license. See LICENSE file in the project root for full license information. namespace Bar { } "; var fixedCode = @"// // Copyright (c) SomeCorp. All rights reserved. // // Licensed under the ??? license. See LICENSE file in the project root for full license information. // namespace Bar { } "; await new VerifyCS.Test { TestCode = testCode, FixedCode = fixedCode, EditorConfig = TestSettingsWithEmptyLines, }.RunAsync(); } } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/EditorFeatures/VisualBasicTest/Recommendations/Statements/EachKeywordRecommenderTests.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.Statements Public Class EachKeywordRecommenderTests Inherits RecommenderTests <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EachNotInMethodBodyTest() VerifyRecommendationsMissing(<MethodBody>|</MethodBody>, "Each") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EachAfterForKeywordTest() VerifyRecommendationsContain(<MethodBody>For |</MethodBody>, "Each") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EachNotAfterTouchingForTest() VerifyRecommendationsMissing(<MethodBody>For|</MethodBody>, "Each") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EachTouchingLoopIdentifierTest() VerifyRecommendationsContain(<MethodBody>For i|</MethodBody>, "Each") End Sub <WorkItem(530953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530953")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotAfterEolTest() VerifyRecommendationsMissing( <MethodBody>For |</MethodBody>, "Each") End Sub <WorkItem(530953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530953")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterExplicitLineContinuationTest() VerifyRecommendationsContain( <MethodBody>For _ |</MethodBody>, "Each") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterExplicitLineContinuationTestCommentsAfterLineContinuation() VerifyRecommendationsContain( <MethodBody>For _ ' Test |</MethodBody>, "Each") End Sub <WorkItem(4946, "http://github.com/dotnet/roslyn/issues/4946")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotInForLoop() VerifyNoRecommendations( <MethodBody>For | = 1 To 100 Next</MethodBody>) 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.Statements Public Class EachKeywordRecommenderTests Inherits RecommenderTests <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EachNotInMethodBodyTest() VerifyRecommendationsMissing(<MethodBody>|</MethodBody>, "Each") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EachAfterForKeywordTest() VerifyRecommendationsContain(<MethodBody>For |</MethodBody>, "Each") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EachNotAfterTouchingForTest() VerifyRecommendationsMissing(<MethodBody>For|</MethodBody>, "Each") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EachTouchingLoopIdentifierTest() VerifyRecommendationsContain(<MethodBody>For i|</MethodBody>, "Each") End Sub <WorkItem(530953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530953")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotAfterEolTest() VerifyRecommendationsMissing( <MethodBody>For |</MethodBody>, "Each") End Sub <WorkItem(530953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530953")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterExplicitLineContinuationTest() VerifyRecommendationsContain( <MethodBody>For _ |</MethodBody>, "Each") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterExplicitLineContinuationTestCommentsAfterLineContinuation() VerifyRecommendationsContain( <MethodBody>For _ ' Test |</MethodBody>, "Each") End Sub <WorkItem(4946, "http://github.com/dotnet/roslyn/issues/4946")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotInForLoop() VerifyNoRecommendations( <MethodBody>For | = 1 To 100 Next</MethodBody>) End Sub End Class End Namespace
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/Features/Core/Portable/Completion/Providers/SymbolMatchPriority.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #pragma warning disable CA1802 // Use literals where appropriate - if any of these are used by an assembly that has IVT it would be breaking to change to constant namespace Microsoft.CodeAnalysis.Completion.Providers { internal static class SymbolMatchPriority { internal static readonly int Keyword = 100; internal static readonly int PreferType = 200; internal static readonly int PreferNamedArgument = 300; internal static readonly int PreferEventOrMethod = 400; internal static readonly int PreferFieldOrProperty = 500; internal static readonly int PreferLocalOrParameterOrRangeVariable = 600; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #pragma warning disable CA1802 // Use literals where appropriate - if any of these are used by an assembly that has IVT it would be breaking to change to constant namespace Microsoft.CodeAnalysis.Completion.Providers { internal static class SymbolMatchPriority { internal static readonly int Keyword = 100; internal static readonly int PreferType = 200; internal static readonly int PreferNamedArgument = 300; internal static readonly int PreferEventOrMethod = 400; internal static readonly int PreferFieldOrProperty = 500; internal static readonly int PreferLocalOrParameterOrRangeVariable = 600; } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/Features/CSharp/Portable/Structure/Providers/IndexerDeclarationStructureProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Structure; namespace Microsoft.CodeAnalysis.CSharp.Structure { internal class IndexerDeclarationStructureProvider : AbstractSyntaxNodeStructureProvider<IndexerDeclarationSyntax> { protected override void CollectBlockSpans( SyntaxToken previousToken, IndexerDeclarationSyntax indexerDeclaration, ref TemporaryArray<BlockSpan> spans, BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken) { CSharpStructureHelpers.CollectCommentBlockSpans(indexerDeclaration, ref spans, optionProvider); // fault tolerance if (indexerDeclaration.AccessorList == null || indexerDeclaration.AccessorList.IsMissing || indexerDeclaration.AccessorList.OpenBraceToken.IsMissing || indexerDeclaration.AccessorList.CloseBraceToken.IsMissing) { return; } SyntaxNodeOrToken current = indexerDeclaration; var nextSibling = current.GetNextSibling(); // Check IsNode to compress blank lines after this node if it is the last child of the parent. // // Indexers are grouped together with properties in Metadata as Source. var compressEmptyLines = optionProvider.IsMetadataAsSource && (!nextSibling.IsNode || nextSibling.IsKind(SyntaxKind.IndexerDeclaration) || nextSibling.IsKind(SyntaxKind.PropertyDeclaration)); spans.AddIfNotNull(CSharpStructureHelpers.CreateBlockSpan( indexerDeclaration, indexerDeclaration.ParameterList.GetLastToken(includeZeroWidth: true), compressEmptyLines: compressEmptyLines, autoCollapse: true, type: BlockTypes.Member, isCollapsible: true)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Structure; namespace Microsoft.CodeAnalysis.CSharp.Structure { internal class IndexerDeclarationStructureProvider : AbstractSyntaxNodeStructureProvider<IndexerDeclarationSyntax> { protected override void CollectBlockSpans( SyntaxToken previousToken, IndexerDeclarationSyntax indexerDeclaration, ref TemporaryArray<BlockSpan> spans, BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken) { CSharpStructureHelpers.CollectCommentBlockSpans(indexerDeclaration, ref spans, optionProvider); // fault tolerance if (indexerDeclaration.AccessorList == null || indexerDeclaration.AccessorList.IsMissing || indexerDeclaration.AccessorList.OpenBraceToken.IsMissing || indexerDeclaration.AccessorList.CloseBraceToken.IsMissing) { return; } SyntaxNodeOrToken current = indexerDeclaration; var nextSibling = current.GetNextSibling(); // Check IsNode to compress blank lines after this node if it is the last child of the parent. // // Indexers are grouped together with properties in Metadata as Source. var compressEmptyLines = optionProvider.IsMetadataAsSource && (!nextSibling.IsNode || nextSibling.IsKind(SyntaxKind.IndexerDeclaration) || nextSibling.IsKind(SyntaxKind.PropertyDeclaration)); spans.AddIfNotNull(CSharpStructureHelpers.CreateBlockSpan( indexerDeclaration, indexerDeclaration.ParameterList.GetLastToken(includeZeroWidth: true), compressEmptyLines: compressEmptyLines, autoCollapse: true, type: BlockTypes.Member, isCollapsible: true)); } } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/Compilers/CSharp/Test/Syntax/Parsing/PatternParsingTests2.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { [CompilerTrait(CompilerFeature.Patterns)] public class PatternParsingTests2 : ParsingTests { private new void UsingExpression(string text, params DiagnosticDescription[] expectedErrors) { UsingExpression(text, options: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.Preview), expectedErrors); } public PatternParsingTests2(ITestOutputHelper output) : base(output) { } [Fact] public void ExtendedPropertySubpattern_01() { UsingExpression(@"e is { a.b.c: p }", TestOptions.Regular10); verify(); UsingExpression(@"e is { a.b.c: p }", TestOptions.Regular9, // (1,8): error CS8773: Feature 'extended property patterns' is not available in C# 9.0. Please use language version 10.0 or greater. // e is { a.b.c: p } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "a.b.c").WithArguments("extended property patterns", "10.0").WithLocation(1, 8)); verify(); void verify() { N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ExpressionColon); { N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "p"); } } } N(SyntaxKind.CloseBraceToken); } } } EOF(); } } [Fact] public void ExtendedPropertySubpattern_02() { UsingExpression(@"e is { {}: p }", // (1,10): error CS1003: Syntax error, ',' expected // e is { {}: p } Diagnostic(ErrorCode.ERR_SyntaxError, ":").WithArguments(",", ":").WithLocation(1, 10), // (1,12): error CS1003: Syntax error, ',' expected // e is { {}: p } Diagnostic(ErrorCode.ERR_SyntaxError, "p").WithArguments(",", "").WithLocation(1, 12)); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } M(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "p"); } } } N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void ExtendedPropertySubpattern_03() { UsingExpression(@"e is { name<T>: p }"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ExpressionColon); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "name"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "p"); } } } N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void ExtendedPropertySubpattern_04() { UsingExpression(@"e is { name[0]: p }", // (1,15): error CS1003: Syntax error, ',' expected // e is { name[0]: p } Diagnostic(ErrorCode.ERR_SyntaxError, ":").WithArguments(",", ":").WithLocation(1, 15), // (1,17): error CS1003: Syntax error, ',' expected // e is { name[0]: p } Diagnostic(ErrorCode.ERR_SyntaxError, "p").WithArguments(",", "").WithLocation(1, 17)); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.TypePattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "name"); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } N(SyntaxKind.CloseBracketToken); } } } } M(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "p"); } } } N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void ExtendedPropertySubpattern_05() { UsingExpression(@"e is { a?.b: p }"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ExpressionColon); { N(SyntaxKind.ConditionalAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.MemberBindingExpression); { N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "p"); } } } N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void ExtendedPropertySubpattern_06() { UsingExpression(@"e is { a->c: p }"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ExpressionColon); { N(SyntaxKind.PointerMemberAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.MinusGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "p"); } } } N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void ExtendedPropertySubpattern_07() { UsingExpression(@"e is { [0]: p }", // (1,8): error CS1001: Identifier expected // e is { [0]: p } Diagnostic(ErrorCode.ERR_IdentifierExpected, "[").WithLocation(1, 8), // (1,10): error CS1003: Syntax error, ',' expected // e is { [0]: p } Diagnostic(ErrorCode.ERR_SyntaxError, "]").WithArguments(",", "]").WithLocation(1, 10), // (1,13): error CS1003: Syntax error, ',' expected // e is { [0]: p } Diagnostic(ErrorCode.ERR_SyntaxError, "p").WithArguments(",", "").WithLocation(1, 13)); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } } M(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "p"); } } } N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void ExtendedPropertySubpattern_08() { UsingExpression(@"e is { not a: p }", // (1,13): error CS1003: Syntax error, ',' expected // e is { not a: p } Diagnostic(ErrorCode.ERR_SyntaxError, ":").WithArguments(",", ":").WithLocation(1, 13), // (1,15): error CS1003: Syntax error, ',' expected // e is { not a: p } Diagnostic(ErrorCode.ERR_SyntaxError, "p").WithArguments(",", "").WithLocation(1, 15)); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NotPattern); { N(SyntaxKind.NotKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } } } M(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "p"); } } } N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void ExtendedPropertySubpattern_09() { UsingExpression(@"e is { x or y: p }", // (1,14): error CS1003: Syntax error, ',' expected // e is { x or y: p } Diagnostic(ErrorCode.ERR_SyntaxError, ":").WithArguments(",", ":").WithLocation(1, 14), // (1,16): error CS1003: Syntax error, ',' expected // e is { x or y: p } Diagnostic(ErrorCode.ERR_SyntaxError, "p").WithArguments(",", "").WithLocation(1, 16)); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.OrPattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.OrKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } } } } M(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "p"); } } } N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void ExtendedPropertySubpattern_10() { UsingExpression(@"e is { 1: p }"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ExpressionColon); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "p"); } } } N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void ExtendedPropertySubpattern_11() { UsingExpression(@"e is { >1: p }", // (1,10): error CS1003: Syntax error, ',' expected // e is { >1: p } Diagnostic(ErrorCode.ERR_SyntaxError, ":").WithArguments(",", ":").WithLocation(1, 10), // (1,12): error CS1003: Syntax error, ',' expected // e is { >1: p } Diagnostic(ErrorCode.ERR_SyntaxError, "p").WithArguments(",", "").WithLocation(1, 12)); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } M(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "p"); } } } N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void ExtendedPropertySubpattern_12() { UsingExpression(@"e is { a!.b: p }"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ExpressionColon); { N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.SuppressNullableWarningExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.ExclamationToken); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "p"); } } } N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void ExtendedPropertySubpattern_13() { UsingExpression(@"e is { a[0].b: p }"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ExpressionColon); { N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.ElementAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.BracketedArgumentList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Argument); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "p"); } } } N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void ExtendedPropertySubpattern_14() { UsingExpression(@"e is { [0].b: p }", // (1,8): error CS1001: Identifier expected // e is { [0].b: p } Diagnostic(ErrorCode.ERR_IdentifierExpected, "[").WithLocation(1, 8), // (1,10): error CS1003: Syntax error, ',' expected // e is { [0].b: p } Diagnostic(ErrorCode.ERR_SyntaxError, "]").WithArguments(",", "]").WithLocation(1, 10), // (1,12): error CS1003: Syntax error, ',' expected // e is { [0].b: p } Diagnostic(ErrorCode.ERR_SyntaxError, "b").WithArguments(",", "").WithLocation(1, 12)); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } } M(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "p"); } } } N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void ExtendedPropertySubpattern_15() { UsingExpression(@"e is { (c?a:b): p }"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ExpressionColon); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.ColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "p"); } } } N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void ExtendedPropertySubpattern_InPositionalPattern() { UsingExpression(@"e is ( a.b.c: p )"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ExpressionColon); { N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "p"); } } } N(SyntaxKind.CloseParenToken); } } } EOF(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { [CompilerTrait(CompilerFeature.Patterns)] public class PatternParsingTests2 : ParsingTests { private new void UsingExpression(string text, params DiagnosticDescription[] expectedErrors) { UsingExpression(text, options: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.Preview), expectedErrors); } public PatternParsingTests2(ITestOutputHelper output) : base(output) { } [Fact] public void ExtendedPropertySubpattern_01() { UsingExpression(@"e is { a.b.c: p }", TestOptions.Regular10); verify(); UsingExpression(@"e is { a.b.c: p }", TestOptions.Regular9, // (1,8): error CS8773: Feature 'extended property patterns' is not available in C# 9.0. Please use language version 10.0 or greater. // e is { a.b.c: p } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "a.b.c").WithArguments("extended property patterns", "10.0").WithLocation(1, 8)); verify(); void verify() { N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ExpressionColon); { N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "p"); } } } N(SyntaxKind.CloseBraceToken); } } } EOF(); } } [Fact] public void ExtendedPropertySubpattern_02() { UsingExpression(@"e is { {}: p }", // (1,10): error CS1003: Syntax error, ',' expected // e is { {}: p } Diagnostic(ErrorCode.ERR_SyntaxError, ":").WithArguments(",", ":").WithLocation(1, 10), // (1,12): error CS1003: Syntax error, ',' expected // e is { {}: p } Diagnostic(ErrorCode.ERR_SyntaxError, "p").WithArguments(",", "").WithLocation(1, 12)); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } M(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "p"); } } } N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void ExtendedPropertySubpattern_03() { UsingExpression(@"e is { name<T>: p }"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ExpressionColon); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "name"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "p"); } } } N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void ExtendedPropertySubpattern_04() { UsingExpression(@"e is { name[0]: p }", // (1,15): error CS1003: Syntax error, ',' expected // e is { name[0]: p } Diagnostic(ErrorCode.ERR_SyntaxError, ":").WithArguments(",", ":").WithLocation(1, 15), // (1,17): error CS1003: Syntax error, ',' expected // e is { name[0]: p } Diagnostic(ErrorCode.ERR_SyntaxError, "p").WithArguments(",", "").WithLocation(1, 17)); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.TypePattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "name"); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } N(SyntaxKind.CloseBracketToken); } } } } M(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "p"); } } } N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void ExtendedPropertySubpattern_05() { UsingExpression(@"e is { a?.b: p }"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ExpressionColon); { N(SyntaxKind.ConditionalAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.MemberBindingExpression); { N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "p"); } } } N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void ExtendedPropertySubpattern_06() { UsingExpression(@"e is { a->c: p }"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ExpressionColon); { N(SyntaxKind.PointerMemberAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.MinusGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "p"); } } } N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void ExtendedPropertySubpattern_07() { UsingExpression(@"e is { [0]: p }", // (1,8): error CS1001: Identifier expected // e is { [0]: p } Diagnostic(ErrorCode.ERR_IdentifierExpected, "[").WithLocation(1, 8), // (1,10): error CS1003: Syntax error, ',' expected // e is { [0]: p } Diagnostic(ErrorCode.ERR_SyntaxError, "]").WithArguments(",", "]").WithLocation(1, 10), // (1,13): error CS1003: Syntax error, ',' expected // e is { [0]: p } Diagnostic(ErrorCode.ERR_SyntaxError, "p").WithArguments(",", "").WithLocation(1, 13)); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } } M(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "p"); } } } N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void ExtendedPropertySubpattern_08() { UsingExpression(@"e is { not a: p }", // (1,13): error CS1003: Syntax error, ',' expected // e is { not a: p } Diagnostic(ErrorCode.ERR_SyntaxError, ":").WithArguments(",", ":").WithLocation(1, 13), // (1,15): error CS1003: Syntax error, ',' expected // e is { not a: p } Diagnostic(ErrorCode.ERR_SyntaxError, "p").WithArguments(",", "").WithLocation(1, 15)); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NotPattern); { N(SyntaxKind.NotKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } } } M(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "p"); } } } N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void ExtendedPropertySubpattern_09() { UsingExpression(@"e is { x or y: p }", // (1,14): error CS1003: Syntax error, ',' expected // e is { x or y: p } Diagnostic(ErrorCode.ERR_SyntaxError, ":").WithArguments(",", ":").WithLocation(1, 14), // (1,16): error CS1003: Syntax error, ',' expected // e is { x or y: p } Diagnostic(ErrorCode.ERR_SyntaxError, "p").WithArguments(",", "").WithLocation(1, 16)); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.OrPattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.OrKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } } } } M(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "p"); } } } N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void ExtendedPropertySubpattern_10() { UsingExpression(@"e is { 1: p }"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ExpressionColon); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "p"); } } } N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void ExtendedPropertySubpattern_11() { UsingExpression(@"e is { >1: p }", // (1,10): error CS1003: Syntax error, ',' expected // e is { >1: p } Diagnostic(ErrorCode.ERR_SyntaxError, ":").WithArguments(",", ":").WithLocation(1, 10), // (1,12): error CS1003: Syntax error, ',' expected // e is { >1: p } Diagnostic(ErrorCode.ERR_SyntaxError, "p").WithArguments(",", "").WithLocation(1, 12)); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } M(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "p"); } } } N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void ExtendedPropertySubpattern_12() { UsingExpression(@"e is { a!.b: p }"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ExpressionColon); { N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.SuppressNullableWarningExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.ExclamationToken); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "p"); } } } N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void ExtendedPropertySubpattern_13() { UsingExpression(@"e is { a[0].b: p }"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ExpressionColon); { N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.ElementAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.BracketedArgumentList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Argument); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "p"); } } } N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void ExtendedPropertySubpattern_14() { UsingExpression(@"e is { [0].b: p }", // (1,8): error CS1001: Identifier expected // e is { [0].b: p } Diagnostic(ErrorCode.ERR_IdentifierExpected, "[").WithLocation(1, 8), // (1,10): error CS1003: Syntax error, ',' expected // e is { [0].b: p } Diagnostic(ErrorCode.ERR_SyntaxError, "]").WithArguments(",", "]").WithLocation(1, 10), // (1,12): error CS1003: Syntax error, ',' expected // e is { [0].b: p } Diagnostic(ErrorCode.ERR_SyntaxError, "b").WithArguments(",", "").WithLocation(1, 12)); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } } M(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "p"); } } } N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void ExtendedPropertySubpattern_15() { UsingExpression(@"e is { (c?a:b): p }"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ExpressionColon); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.ColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "p"); } } } N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void ExtendedPropertySubpattern_InPositionalPattern() { UsingExpression(@"e is ( a.b.c: p )"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ExpressionColon); { N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "p"); } } } N(SyntaxKind.CloseParenToken); } } } EOF(); } } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/EditorFeatures/CSharp/xlf/CSharpEditorResources.zh-Hans.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="zh-Hans" original="../CSharpEditorResources.resx"> <body> <trans-unit id="Add_Missing_Usings_on_Paste"> <source>Add Missing Usings on Paste</source> <target state="translated">粘贴时添加缺少的 Usings</target> <note>"usings" is a language specific term and should not be localized</note> </trans-unit> <trans-unit id="Adding_missing_usings"> <source>Adding missing usings...</source> <target state="translated">正在添加缺少的 usings…</target> <note>Shown in a thread await dialog. "usings" is a language specific term and should not be localized</note> </trans-unit> <trans-unit id="Avoid_expression_statements_that_implicitly_ignore_value"> <source>Avoid expression statements that implicitly ignore value</source> <target state="translated">避免会隐式忽略值的表达式语句</target> <note /> </trans-unit> <trans-unit id="Avoid_unused_value_assignments"> <source>Avoid unused value assignments</source> <target state="translated">避免未使用的值赋值</target> <note /> </trans-unit> <trans-unit id="Chosen_version_0"> <source>Chosen version: '{0}'</source> <target state="translated">所选版本: "{0}"</target> <note /> </trans-unit> <trans-unit id="Complete_statement_on_semicolon"> <source>Complete statement on ;</source> <target state="translated">完成语句时间;</target> <note /> </trans-unit> <trans-unit id="Could_not_find_by_name_0"> <source>Could not find by name: '{0}'</source> <target state="translated">无法按名称“{0}”查找 </target> <note /> </trans-unit> <trans-unit id="Decompilation_log"> <source>Decompilation log</source> <target state="translated">反编译日志</target> <note /> </trans-unit> <trans-unit id="Discard"> <source>Discard</source> <target state="translated">放弃</target> <note /> </trans-unit> <trans-unit id="Elsewhere"> <source>Elsewhere</source> <target state="translated">其他位置</target> <note /> </trans-unit> <trans-unit id="Fix_interpolated_verbatim_string"> <source>Fix interpolated verbatim string</source> <target state="translated">修复插值的逐字字符串</target> <note /> </trans-unit> <trans-unit id="For_built_in_types"> <source>For built-in types</source> <target state="translated">对于内置类型</target> <note /> </trans-unit> <trans-unit id="Found_0_assemblies_for_1"> <source>Found '{0}' assemblies for '{1}':</source> <target state="translated">找到 “{1}”的“{0}”个程序集:</target> <note /> </trans-unit> <trans-unit id="Found_exact_match_0"> <source>Found exact match: '{0}'</source> <target state="translated">找到完全匹配: "{0}"</target> <note /> </trans-unit> <trans-unit id="Found_higher_version_match_0"> <source>Found higher version match: '{0}'</source> <target state="translated">找到较高版本匹配: "{0}"</target> <note /> </trans-unit> <trans-unit id="Found_single_assembly_0"> <source>Found single assembly: '{0}'</source> <target state="translated">找到单个程序集: "{0}"</target> <note /> </trans-unit> <trans-unit id="Generate_Event_Subscription"> <source>Generate Event Subscription</source> <target state="translated">生成事件订阅</target> <note /> </trans-unit> <trans-unit id="Ignore_spaces_in_declaration_statements"> <source>Ignore spaces in declaration statements</source> <target state="translated">忽略声明语句中的空格</target> <note /> </trans-unit> <trans-unit id="Indent_block_contents"> <source>Indent block contents</source> <target state="translated">缩进块内容</target> <note /> </trans-unit> <trans-unit id="Indent_case_contents"> <source>Indent case contents</source> <target state="translated">缩进 case 内容</target> <note /> </trans-unit> <trans-unit id="Indent_case_contents_when_block"> <source>Indent case contents (when block)</source> <target state="translated">缩进 case 内容(阻止时)</target> <note /> </trans-unit> <trans-unit id="Indent_case_labels"> <source>Indent case labels</source> <target state="translated">缩进 case 标签</target> <note /> </trans-unit> <trans-unit id="Indent_open_and_close_braces"> <source>Indent open and close braces</source> <target state="translated">缩进左大括号和右大括号</target> <note /> </trans-unit> <trans-unit id="Insert_space_after_cast"> <source>Insert space after cast</source> <target state="translated">在强制转换后插入空格</target> <note /> </trans-unit> <trans-unit id="Insert_space_after_colon_for_base_or_interface_in_type_declaration"> <source>Insert space after colon for base or interface in type declaration</source> <target state="translated">在类型声明中的“base”或接口的冒号后插入空格</target> <note /> </trans-unit> <trans-unit id="Insert_space_after_comma"> <source>Insert space after comma</source> <target state="translated">在逗号后插入空格</target> <note /> </trans-unit> <trans-unit id="Insert_space_after_dot"> <source>Insert space after dot</source> <target state="translated">在点后插入空格</target> <note /> </trans-unit> <trans-unit id="Insert_space_after_keywords_in_control_flow_statements"> <source>Insert space after keywords in control flow statements</source> <target state="translated">在控制流语句中的关键字后面插入空格</target> <note /> </trans-unit> <trans-unit id="Insert_space_after_semicolon_in_for_statement"> <source>Insert space after semicolon in "for" statement</source> <target state="translated">在“for”语句中的分号后插入空格</target> <note /> </trans-unit> <trans-unit id="Insert_space_before_colon_for_base_or_interface_in_type_declaration"> <source>Insert space before colon for base or interface in type declaration</source> <target state="translated">在类型声明中的“base”或接口的冒号前插入空格</target> <note /> </trans-unit> <trans-unit id="Insert_space_before_comma"> <source>Insert space before comma</source> <target state="translated">在逗号前插入空格</target> <note /> </trans-unit> <trans-unit id="Insert_space_before_dot"> <source>Insert space before dot</source> <target state="translated">在点前插入空格</target> <note /> </trans-unit> <trans-unit id="Insert_space_before_open_square_bracket"> <source>Insert space before open square bracket</source> <target state="translated">在左方括号前插入空格</target> <note /> </trans-unit> <trans-unit id="Insert_space_before_semicolon_in_for_statement"> <source>Insert space before semicolon in "for" statement</source> <target state="translated">在“for”语句中的分号前插入空格</target> <note /> </trans-unit> <trans-unit id="Insert_space_between_method_name_and_its_opening_parenthesis1"> <source>Insert space between method name and its opening parenthesis</source> <target state="translated">在方法名称与其左括号之间插入空格</target> <note /> </trans-unit> <trans-unit id="Insert_space_between_method_name_and_its_opening_parenthesis2"> <source>Insert space between method name and its opening parenthesis</source> <target state="translated">在方法名称与其左括号之间插入空格</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_argument_list_parentheses"> <source>Insert space within argument list parentheses</source> <target state="translated">在参数列表的括号中插入空格</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_empty_argument_list_parentheses"> <source>Insert space within empty argument list parentheses</source> <target state="translated">在空参数列表的括号中插入空格</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_empty_parameter_list_parentheses"> <source>Insert space within empty parameter list parentheses</source> <target state="translated">在空参数列表的括号中插入空格</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_empty_square_brackets"> <source>Insert space within empty square brackets</source> <target state="translated">在空方括号中插入空格</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_parameter_list_parentheses"> <source>Insert space within parameter list parentheses</source> <target state="translated">在参数列表的括号中插入空格</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_parentheses_of_expressions"> <source>Insert space within parentheses of expressions</source> <target state="translated">在表达式的括号中插入空格</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_parentheses_of_type_casts"> <source>Insert space within parentheses of type casts</source> <target state="translated">在类型转换的括号中插入空格</target> <note /> </trans-unit> <trans-unit id="Insert_spaces_within_parentheses_of_control_flow_statements"> <source>Insert spaces within parentheses of control flow statements</source> <target state="translated">在控制流语句的括号中插入空格</target> <note /> </trans-unit> <trans-unit id="Insert_spaces_within_square_brackets"> <source>Insert spaces within square brackets</source> <target state="translated">在方括号中插入空格</target> <note /> </trans-unit> <trans-unit id="Inside_namespace"> <source>Inside namespace</source> <target state="translated">在命名空间中</target> <note /> </trans-unit> <trans-unit id="Label_Indentation"> <source>Label Indentation</source> <target state="translated">标签缩进</target> <note /> </trans-unit> <trans-unit id="Leave_block_on_single_line"> <source>Leave block on single line</source> <target state="translated">将块保留在一行上</target> <note /> </trans-unit> <trans-unit id="Leave_statements_and_member_declarations_on_the_same_line"> <source>Leave statements and member declarations on the same line</source> <target state="translated">将语句和成员声明保留在同一行上</target> <note /> </trans-unit> <trans-unit id="Load_from_0"> <source>Load from: '{0}'</source> <target state="translated">从以下位置加载: "{0}"</target> <note /> </trans-unit> <trans-unit id="Module_not_found"> <source>Module not found!</source> <target state="translated">找不到模块!</target> <note /> </trans-unit> <trans-unit id="Never"> <source>Never</source> <target state="translated">从不</target> <note /> </trans-unit> <trans-unit id="Outside_namespace"> <source>Outside namespace</source> <target state="translated">命名空间外</target> <note /> </trans-unit> <trans-unit id="Place_catch_on_new_line"> <source>Place "catch" on new line</source> <target state="translated">将“catch”置于新行</target> <note /> </trans-unit> <trans-unit id="Place_else_on_new_line"> <source>Place "else" on new line</source> <target state="translated">将“else”置于新行</target> <note /> </trans-unit> <trans-unit id="Place_finally_on_new_line"> <source>Place "finally" on new line</source> <target state="translated">将“finally”置于新行</target> <note /> </trans-unit> <trans-unit id="Place_members_in_anonymous_types_on_new_line"> <source>Place members in anonymous types on new line</source> <target state="translated">将匿名类型中的成员置于新行</target> <note /> </trans-unit> <trans-unit id="Place_members_in_object_initializers_on_new_line"> <source>Place members in object initializers on new line</source> <target state="translated">将对象初始值设定项中的成员置于新行</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_anonymous_methods"> <source>Place open brace on new line for anonymous methods</source> <target state="translated">将匿名方法的左大括号置于新行</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_anonymous_types"> <source>Place open brace on new line for anonymous types</source> <target state="translated">将匿名类型的左大括号置于新行</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_control_blocks"> <source>Place open brace on new line for control blocks</source> <target state="translated">将控制块的左大括号置于新行</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_lambda_expression"> <source>Place open brace on new line for lambda expression</source> <target state="translated">将 lambda 表达式的左大括号置于新行</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_methods_local_functions"> <source>Place open brace on new line for methods and local functions</source> <target state="translated">将方法和本地函数的左大括号置于新行</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_object_collection_array_and_with_initializers"> <source>Place open brace on new line for object, collection, array, and with initializers</source> <target state="translated">对于对象、集合、数组和 with 初始值设定项,另起一行放置左花括号</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_properties_indexers_and_events"> <source>Place open brace on new line for properties, indexers, and events</source> <target state="translated">将左大括号放置在新行中,以表示属性、索引器和事件</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_property_indexer_and_event_accessors"> <source>Place open brace on new line for property, indexer, and event accessors</source> <target state="translated">将左大括号放置在新行中,以表示属性、索引器和事件访问器</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_types"> <source>Place open brace on new line for types</source> <target state="translated">将类型的左大括号置于新行</target> <note /> </trans-unit> <trans-unit id="Place_query_expression_clauses_on_new_line"> <source>Place query expression clauses on new line</source> <target state="translated">将查询表达式子句置于新行</target> <note /> </trans-unit> <trans-unit id="Prefer_conditional_delegate_call"> <source>Prefer conditional delegate call</source> <target state="translated">更喜欢有条件的委托调用</target> <note /> </trans-unit> <trans-unit id="Prefer_deconstructed_variable_declaration"> <source>Prefer deconstructed variable declaration</source> <target state="translated">首选析构变量声明</target> <note /> </trans-unit> <trans-unit id="Prefer_explicit_type"> <source>Prefer explicit type</source> <target state="translated">首选显式类型</target> <note /> </trans-unit> <trans-unit id="Prefer_index_operator"> <source>Prefer index operator</source> <target state="translated">首选索引运算符</target> <note /> </trans-unit> <trans-unit id="Prefer_inlined_variable_declaration"> <source>Prefer inlined variable declaration</source> <target state="translated">首选内联的变量声明</target> <note /> </trans-unit> <trans-unit id="Prefer_local_function_over_anonymous_function"> <source>Prefer local function over anonymous function</source> <target state="translated">首选本地函数而不是匿名函数</target> <note /> </trans-unit> <trans-unit id="Prefer_null_check_over_type_check"> <source>Prefer 'null' check over type check</source> <target state="translated">与类型检查相比,首选 “Null” 检查</target> <note /> </trans-unit> <trans-unit id="Prefer_pattern_matching"> <source>Prefer pattern matching</source> <target state="translated">首选模式匹配</target> <note /> </trans-unit> <trans-unit id="Prefer_pattern_matching_over_as_with_null_check"> <source>Prefer pattern matching over 'as' with 'null' check</source> <target state="translated">使用 "null" 检查时首选模式匹配而不是 "as"</target> <note /> </trans-unit> <trans-unit id="Prefer_pattern_matching_over_is_with_cast_check"> <source>Prefer pattern matching over 'is' with 'cast' check</source> <target state="translated">使用 "cast" 检查时首选模式匹配而不是 "is"</target> <note /> </trans-unit> <trans-unit id="Prefer_pattern_matching_over_mixed_type_check"> <source>Prefer pattern matching over mixed type check</source> <target state="translated">首选模式匹配而不是混合类型检查</target> <note /> </trans-unit> <trans-unit id="Prefer_range_operator"> <source>Prefer range operator</source> <target state="translated">首选范围运算符</target> <note /> </trans-unit> <trans-unit id="Prefer_simple_default_expression"> <source>Prefer simple 'default' expression</source> <target state="translated">偏爱简单的 "default" 表达式</target> <note /> </trans-unit> <trans-unit id="Prefer_simple_using_statement"> <source>Prefer simple 'using' statement</source> <target state="translated">首选简单的 "using" 语句</target> <note /> </trans-unit> <trans-unit id="Prefer_static_local_functions"> <source>Prefer static local functions</source> <target state="translated">首选静态本地函数</target> <note /> </trans-unit> <trans-unit id="Prefer_switch_expression"> <source>Prefer switch expression</source> <target state="translated">首选 switch 表达式</target> <note /> </trans-unit> <trans-unit id="Prefer_throw_expression"> <source>Prefer throw-expression</source> <target state="translated">更喜欢 throw 表达式</target> <note /> </trans-unit> <trans-unit id="Prefer_var"> <source>Prefer 'var'</source> <target state="translated">首选 "var"</target> <note /> </trans-unit> <trans-unit id="Preferred_using_directive_placement"> <source>Preferred 'using' directive placement</source> <target state="translated">首选 "using" 指令放置</target> <note /> </trans-unit> <trans-unit id="Press_TAB_to_insert"> <source> (Press TAB to insert)</source> <target state="translated">(按 Tab 插入)</target> <note /> </trans-unit> <trans-unit id="Resolve_0"> <source>Resolve: '{0}'</source> <target state="translated">解析: "{0}"</target> <note /> </trans-unit> <trans-unit id="Resolve_module_0_of_1"> <source>Resolve module: '{0}' of '{1}'</source> <target state="translated">解析模块: "{0}" 个(共 "{1}" 个)</target> <note /> </trans-unit> <trans-unit id="Set_spacing_for_operators"> <source>Set spacing for operators</source> <target state="translated">设置运算符的间距</target> <note /> </trans-unit> <trans-unit id="Smart_Indenting"> <source>Smart Indenting</source> <target state="translated">智能缩进</target> <note /> </trans-unit> <trans-unit id="Split_string"> <source>Split string</source> <target state="translated">拆分字符串</target> <note /> </trans-unit> <trans-unit id="Unused_local"> <source>Unused local</source> <target state="translated">未使用的本地</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_accessors"> <source>Use expression body for accessors</source> <target state="translated">使用访问器的表达式主体</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_constructors"> <source>Use expression body for constructors</source> <target state="translated">使用构造函数的表达式主体</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_indexers"> <source>Use expression body for indexers</source> <target state="translated">使用索引器的表达式主体</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_lambdas"> <source>Use expression body for lambdas</source> <target state="translated">使用 lambdas 的表达式主体</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_local_functions"> <source>Use expression body for local functions</source> <target state="translated">将表达式主体用于本地函数</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_methods"> <source>Use expression body for methods</source> <target state="translated">使用方法的表达式主体</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_operators"> <source>Use expression body for operators</source> <target state="translated">使用运算符的表达式主体</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_properties"> <source>Use expression body for properties</source> <target state="translated">使用属性的表达式主体</target> <note /> </trans-unit> <trans-unit id="WARN_Version_mismatch_Expected_0_Got_1"> <source>WARN: Version mismatch. Expected: '{0}', Got: '{1}'</source> <target state="translated">警告: 版本不匹配。应为: "{0}",实际为: "{1}"</target> <note /> </trans-unit> <trans-unit id="When_on_single_line"> <source>When on single line</source> <target state="translated">处于单行上时</target> <note /> </trans-unit> <trans-unit id="When_possible"> <source>When possible</source> <target state="translated">在可能的情况下</target> <note /> </trans-unit> <trans-unit id="When_variable_type_is_apparent"> <source>When variable type is apparent</source> <target state="translated">当变量类型明显时</target> <note /> </trans-unit> <trans-unit id="_0_items_in_cache"> <source>'{0}' items in cache</source> <target state="translated">缓存中的 {0} 项</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="zh-Hans" original="../CSharpEditorResources.resx"> <body> <trans-unit id="Add_Missing_Usings_on_Paste"> <source>Add Missing Usings on Paste</source> <target state="translated">粘贴时添加缺少的 Usings</target> <note>"usings" is a language specific term and should not be localized</note> </trans-unit> <trans-unit id="Adding_missing_usings"> <source>Adding missing usings...</source> <target state="translated">正在添加缺少的 usings…</target> <note>Shown in a thread await dialog. "usings" is a language specific term and should not be localized</note> </trans-unit> <trans-unit id="Avoid_expression_statements_that_implicitly_ignore_value"> <source>Avoid expression statements that implicitly ignore value</source> <target state="translated">避免会隐式忽略值的表达式语句</target> <note /> </trans-unit> <trans-unit id="Avoid_unused_value_assignments"> <source>Avoid unused value assignments</source> <target state="translated">避免未使用的值赋值</target> <note /> </trans-unit> <trans-unit id="Chosen_version_0"> <source>Chosen version: '{0}'</source> <target state="translated">所选版本: "{0}"</target> <note /> </trans-unit> <trans-unit id="Complete_statement_on_semicolon"> <source>Complete statement on ;</source> <target state="translated">完成语句时间;</target> <note /> </trans-unit> <trans-unit id="Could_not_find_by_name_0"> <source>Could not find by name: '{0}'</source> <target state="translated">无法按名称“{0}”查找 </target> <note /> </trans-unit> <trans-unit id="Decompilation_log"> <source>Decompilation log</source> <target state="translated">反编译日志</target> <note /> </trans-unit> <trans-unit id="Discard"> <source>Discard</source> <target state="translated">放弃</target> <note /> </trans-unit> <trans-unit id="Elsewhere"> <source>Elsewhere</source> <target state="translated">其他位置</target> <note /> </trans-unit> <trans-unit id="Fix_interpolated_verbatim_string"> <source>Fix interpolated verbatim string</source> <target state="translated">修复插值的逐字字符串</target> <note /> </trans-unit> <trans-unit id="For_built_in_types"> <source>For built-in types</source> <target state="translated">对于内置类型</target> <note /> </trans-unit> <trans-unit id="Found_0_assemblies_for_1"> <source>Found '{0}' assemblies for '{1}':</source> <target state="translated">找到 “{1}”的“{0}”个程序集:</target> <note /> </trans-unit> <trans-unit id="Found_exact_match_0"> <source>Found exact match: '{0}'</source> <target state="translated">找到完全匹配: "{0}"</target> <note /> </trans-unit> <trans-unit id="Found_higher_version_match_0"> <source>Found higher version match: '{0}'</source> <target state="translated">找到较高版本匹配: "{0}"</target> <note /> </trans-unit> <trans-unit id="Found_single_assembly_0"> <source>Found single assembly: '{0}'</source> <target state="translated">找到单个程序集: "{0}"</target> <note /> </trans-unit> <trans-unit id="Generate_Event_Subscription"> <source>Generate Event Subscription</source> <target state="translated">生成事件订阅</target> <note /> </trans-unit> <trans-unit id="Ignore_spaces_in_declaration_statements"> <source>Ignore spaces in declaration statements</source> <target state="translated">忽略声明语句中的空格</target> <note /> </trans-unit> <trans-unit id="Indent_block_contents"> <source>Indent block contents</source> <target state="translated">缩进块内容</target> <note /> </trans-unit> <trans-unit id="Indent_case_contents"> <source>Indent case contents</source> <target state="translated">缩进 case 内容</target> <note /> </trans-unit> <trans-unit id="Indent_case_contents_when_block"> <source>Indent case contents (when block)</source> <target state="translated">缩进 case 内容(阻止时)</target> <note /> </trans-unit> <trans-unit id="Indent_case_labels"> <source>Indent case labels</source> <target state="translated">缩进 case 标签</target> <note /> </trans-unit> <trans-unit id="Indent_open_and_close_braces"> <source>Indent open and close braces</source> <target state="translated">缩进左大括号和右大括号</target> <note /> </trans-unit> <trans-unit id="Insert_space_after_cast"> <source>Insert space after cast</source> <target state="translated">在强制转换后插入空格</target> <note /> </trans-unit> <trans-unit id="Insert_space_after_colon_for_base_or_interface_in_type_declaration"> <source>Insert space after colon for base or interface in type declaration</source> <target state="translated">在类型声明中的“base”或接口的冒号后插入空格</target> <note /> </trans-unit> <trans-unit id="Insert_space_after_comma"> <source>Insert space after comma</source> <target state="translated">在逗号后插入空格</target> <note /> </trans-unit> <trans-unit id="Insert_space_after_dot"> <source>Insert space after dot</source> <target state="translated">在点后插入空格</target> <note /> </trans-unit> <trans-unit id="Insert_space_after_keywords_in_control_flow_statements"> <source>Insert space after keywords in control flow statements</source> <target state="translated">在控制流语句中的关键字后面插入空格</target> <note /> </trans-unit> <trans-unit id="Insert_space_after_semicolon_in_for_statement"> <source>Insert space after semicolon in "for" statement</source> <target state="translated">在“for”语句中的分号后插入空格</target> <note /> </trans-unit> <trans-unit id="Insert_space_before_colon_for_base_or_interface_in_type_declaration"> <source>Insert space before colon for base or interface in type declaration</source> <target state="translated">在类型声明中的“base”或接口的冒号前插入空格</target> <note /> </trans-unit> <trans-unit id="Insert_space_before_comma"> <source>Insert space before comma</source> <target state="translated">在逗号前插入空格</target> <note /> </trans-unit> <trans-unit id="Insert_space_before_dot"> <source>Insert space before dot</source> <target state="translated">在点前插入空格</target> <note /> </trans-unit> <trans-unit id="Insert_space_before_open_square_bracket"> <source>Insert space before open square bracket</source> <target state="translated">在左方括号前插入空格</target> <note /> </trans-unit> <trans-unit id="Insert_space_before_semicolon_in_for_statement"> <source>Insert space before semicolon in "for" statement</source> <target state="translated">在“for”语句中的分号前插入空格</target> <note /> </trans-unit> <trans-unit id="Insert_space_between_method_name_and_its_opening_parenthesis1"> <source>Insert space between method name and its opening parenthesis</source> <target state="translated">在方法名称与其左括号之间插入空格</target> <note /> </trans-unit> <trans-unit id="Insert_space_between_method_name_and_its_opening_parenthesis2"> <source>Insert space between method name and its opening parenthesis</source> <target state="translated">在方法名称与其左括号之间插入空格</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_argument_list_parentheses"> <source>Insert space within argument list parentheses</source> <target state="translated">在参数列表的括号中插入空格</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_empty_argument_list_parentheses"> <source>Insert space within empty argument list parentheses</source> <target state="translated">在空参数列表的括号中插入空格</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_empty_parameter_list_parentheses"> <source>Insert space within empty parameter list parentheses</source> <target state="translated">在空参数列表的括号中插入空格</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_empty_square_brackets"> <source>Insert space within empty square brackets</source> <target state="translated">在空方括号中插入空格</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_parameter_list_parentheses"> <source>Insert space within parameter list parentheses</source> <target state="translated">在参数列表的括号中插入空格</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_parentheses_of_expressions"> <source>Insert space within parentheses of expressions</source> <target state="translated">在表达式的括号中插入空格</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_parentheses_of_type_casts"> <source>Insert space within parentheses of type casts</source> <target state="translated">在类型转换的括号中插入空格</target> <note /> </trans-unit> <trans-unit id="Insert_spaces_within_parentheses_of_control_flow_statements"> <source>Insert spaces within parentheses of control flow statements</source> <target state="translated">在控制流语句的括号中插入空格</target> <note /> </trans-unit> <trans-unit id="Insert_spaces_within_square_brackets"> <source>Insert spaces within square brackets</source> <target state="translated">在方括号中插入空格</target> <note /> </trans-unit> <trans-unit id="Inside_namespace"> <source>Inside namespace</source> <target state="translated">在命名空间中</target> <note /> </trans-unit> <trans-unit id="Label_Indentation"> <source>Label Indentation</source> <target state="translated">标签缩进</target> <note /> </trans-unit> <trans-unit id="Leave_block_on_single_line"> <source>Leave block on single line</source> <target state="translated">将块保留在一行上</target> <note /> </trans-unit> <trans-unit id="Leave_statements_and_member_declarations_on_the_same_line"> <source>Leave statements and member declarations on the same line</source> <target state="translated">将语句和成员声明保留在同一行上</target> <note /> </trans-unit> <trans-unit id="Load_from_0"> <source>Load from: '{0}'</source> <target state="translated">从以下位置加载: "{0}"</target> <note /> </trans-unit> <trans-unit id="Module_not_found"> <source>Module not found!</source> <target state="translated">找不到模块!</target> <note /> </trans-unit> <trans-unit id="Never"> <source>Never</source> <target state="translated">从不</target> <note /> </trans-unit> <trans-unit id="Outside_namespace"> <source>Outside namespace</source> <target state="translated">命名空间外</target> <note /> </trans-unit> <trans-unit id="Place_catch_on_new_line"> <source>Place "catch" on new line</source> <target state="translated">将“catch”置于新行</target> <note /> </trans-unit> <trans-unit id="Place_else_on_new_line"> <source>Place "else" on new line</source> <target state="translated">将“else”置于新行</target> <note /> </trans-unit> <trans-unit id="Place_finally_on_new_line"> <source>Place "finally" on new line</source> <target state="translated">将“finally”置于新行</target> <note /> </trans-unit> <trans-unit id="Place_members_in_anonymous_types_on_new_line"> <source>Place members in anonymous types on new line</source> <target state="translated">将匿名类型中的成员置于新行</target> <note /> </trans-unit> <trans-unit id="Place_members_in_object_initializers_on_new_line"> <source>Place members in object initializers on new line</source> <target state="translated">将对象初始值设定项中的成员置于新行</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_anonymous_methods"> <source>Place open brace on new line for anonymous methods</source> <target state="translated">将匿名方法的左大括号置于新行</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_anonymous_types"> <source>Place open brace on new line for anonymous types</source> <target state="translated">将匿名类型的左大括号置于新行</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_control_blocks"> <source>Place open brace on new line for control blocks</source> <target state="translated">将控制块的左大括号置于新行</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_lambda_expression"> <source>Place open brace on new line for lambda expression</source> <target state="translated">将 lambda 表达式的左大括号置于新行</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_methods_local_functions"> <source>Place open brace on new line for methods and local functions</source> <target state="translated">将方法和本地函数的左大括号置于新行</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_object_collection_array_and_with_initializers"> <source>Place open brace on new line for object, collection, array, and with initializers</source> <target state="translated">对于对象、集合、数组和 with 初始值设定项,另起一行放置左花括号</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_properties_indexers_and_events"> <source>Place open brace on new line for properties, indexers, and events</source> <target state="translated">将左大括号放置在新行中,以表示属性、索引器和事件</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_property_indexer_and_event_accessors"> <source>Place open brace on new line for property, indexer, and event accessors</source> <target state="translated">将左大括号放置在新行中,以表示属性、索引器和事件访问器</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_types"> <source>Place open brace on new line for types</source> <target state="translated">将类型的左大括号置于新行</target> <note /> </trans-unit> <trans-unit id="Place_query_expression_clauses_on_new_line"> <source>Place query expression clauses on new line</source> <target state="translated">将查询表达式子句置于新行</target> <note /> </trans-unit> <trans-unit id="Prefer_conditional_delegate_call"> <source>Prefer conditional delegate call</source> <target state="translated">更喜欢有条件的委托调用</target> <note /> </trans-unit> <trans-unit id="Prefer_deconstructed_variable_declaration"> <source>Prefer deconstructed variable declaration</source> <target state="translated">首选析构变量声明</target> <note /> </trans-unit> <trans-unit id="Prefer_explicit_type"> <source>Prefer explicit type</source> <target state="translated">首选显式类型</target> <note /> </trans-unit> <trans-unit id="Prefer_index_operator"> <source>Prefer index operator</source> <target state="translated">首选索引运算符</target> <note /> </trans-unit> <trans-unit id="Prefer_inlined_variable_declaration"> <source>Prefer inlined variable declaration</source> <target state="translated">首选内联的变量声明</target> <note /> </trans-unit> <trans-unit id="Prefer_local_function_over_anonymous_function"> <source>Prefer local function over anonymous function</source> <target state="translated">首选本地函数而不是匿名函数</target> <note /> </trans-unit> <trans-unit id="Prefer_null_check_over_type_check"> <source>Prefer 'null' check over type check</source> <target state="translated">与类型检查相比,首选 “Null” 检查</target> <note /> </trans-unit> <trans-unit id="Prefer_pattern_matching"> <source>Prefer pattern matching</source> <target state="translated">首选模式匹配</target> <note /> </trans-unit> <trans-unit id="Prefer_pattern_matching_over_as_with_null_check"> <source>Prefer pattern matching over 'as' with 'null' check</source> <target state="translated">使用 "null" 检查时首选模式匹配而不是 "as"</target> <note /> </trans-unit> <trans-unit id="Prefer_pattern_matching_over_is_with_cast_check"> <source>Prefer pattern matching over 'is' with 'cast' check</source> <target state="translated">使用 "cast" 检查时首选模式匹配而不是 "is"</target> <note /> </trans-unit> <trans-unit id="Prefer_pattern_matching_over_mixed_type_check"> <source>Prefer pattern matching over mixed type check</source> <target state="translated">首选模式匹配而不是混合类型检查</target> <note /> </trans-unit> <trans-unit id="Prefer_range_operator"> <source>Prefer range operator</source> <target state="translated">首选范围运算符</target> <note /> </trans-unit> <trans-unit id="Prefer_simple_default_expression"> <source>Prefer simple 'default' expression</source> <target state="translated">偏爱简单的 "default" 表达式</target> <note /> </trans-unit> <trans-unit id="Prefer_simple_using_statement"> <source>Prefer simple 'using' statement</source> <target state="translated">首选简单的 "using" 语句</target> <note /> </trans-unit> <trans-unit id="Prefer_static_local_functions"> <source>Prefer static local functions</source> <target state="translated">首选静态本地函数</target> <note /> </trans-unit> <trans-unit id="Prefer_switch_expression"> <source>Prefer switch expression</source> <target state="translated">首选 switch 表达式</target> <note /> </trans-unit> <trans-unit id="Prefer_throw_expression"> <source>Prefer throw-expression</source> <target state="translated">更喜欢 throw 表达式</target> <note /> </trans-unit> <trans-unit id="Prefer_var"> <source>Prefer 'var'</source> <target state="translated">首选 "var"</target> <note /> </trans-unit> <trans-unit id="Preferred_using_directive_placement"> <source>Preferred 'using' directive placement</source> <target state="translated">首选 "using" 指令放置</target> <note /> </trans-unit> <trans-unit id="Press_TAB_to_insert"> <source> (Press TAB to insert)</source> <target state="translated">(按 Tab 插入)</target> <note /> </trans-unit> <trans-unit id="Resolve_0"> <source>Resolve: '{0}'</source> <target state="translated">解析: "{0}"</target> <note /> </trans-unit> <trans-unit id="Resolve_module_0_of_1"> <source>Resolve module: '{0}' of '{1}'</source> <target state="translated">解析模块: "{0}" 个(共 "{1}" 个)</target> <note /> </trans-unit> <trans-unit id="Set_spacing_for_operators"> <source>Set spacing for operators</source> <target state="translated">设置运算符的间距</target> <note /> </trans-unit> <trans-unit id="Smart_Indenting"> <source>Smart Indenting</source> <target state="translated">智能缩进</target> <note /> </trans-unit> <trans-unit id="Split_string"> <source>Split string</source> <target state="translated">拆分字符串</target> <note /> </trans-unit> <trans-unit id="Unused_local"> <source>Unused local</source> <target state="translated">未使用的本地</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_accessors"> <source>Use expression body for accessors</source> <target state="translated">使用访问器的表达式主体</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_constructors"> <source>Use expression body for constructors</source> <target state="translated">使用构造函数的表达式主体</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_indexers"> <source>Use expression body for indexers</source> <target state="translated">使用索引器的表达式主体</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_lambdas"> <source>Use expression body for lambdas</source> <target state="translated">使用 lambdas 的表达式主体</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_local_functions"> <source>Use expression body for local functions</source> <target state="translated">将表达式主体用于本地函数</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_methods"> <source>Use expression body for methods</source> <target state="translated">使用方法的表达式主体</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_operators"> <source>Use expression body for operators</source> <target state="translated">使用运算符的表达式主体</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_properties"> <source>Use expression body for properties</source> <target state="translated">使用属性的表达式主体</target> <note /> </trans-unit> <trans-unit id="WARN_Version_mismatch_Expected_0_Got_1"> <source>WARN: Version mismatch. Expected: '{0}', Got: '{1}'</source> <target state="translated">警告: 版本不匹配。应为: "{0}",实际为: "{1}"</target> <note /> </trans-unit> <trans-unit id="When_on_single_line"> <source>When on single line</source> <target state="translated">处于单行上时</target> <note /> </trans-unit> <trans-unit id="When_possible"> <source>When possible</source> <target state="translated">在可能的情况下</target> <note /> </trans-unit> <trans-unit id="When_variable_type_is_apparent"> <source>When variable type is apparent</source> <target state="translated">当变量类型明显时</target> <note /> </trans-unit> <trans-unit id="_0_items_in_cache"> <source>'{0}' items in cache</source> <target state="translated">缓存中的 {0} 项</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/VisualStudio/Core/Def/EditorConfigSettings/Whitespace/ViewModel/WhitespaceViewModel.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.DataProvider; using Microsoft.Internal.VisualStudio.Shell.TableControl; using Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common; using Microsoft.VisualStudio.Shell.TableControl; using Microsoft.VisualStudio.Shell.TableManager; namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Whitespace.ViewModel { internal partial class WhitespaceViewModel : SettingsViewModelBase< WhitespaceSetting, WhitespaceViewModel.SettingsSnapshotFactory, WhitespaceViewModel.SettingsEntriesSnapshot> { public WhitespaceViewModel(ISettingsProvider<WhitespaceSetting> data, IWpfTableControlProvider controlProvider, ITableManagerProvider tableMangerProvider) : base(data, controlProvider, tableMangerProvider) { } public override string Identifier => "Whitespace"; protected override SettingsSnapshotFactory CreateSnapshotFactory(ISettingsProvider<WhitespaceSetting> data) => new(data); protected override IEnumerable<ColumnState2> GetInitialColumnStates() => new[] { new ColumnState2(ColumnDefinitions.Whitespace.Category, isVisible: false, width: 0, groupingPriority: 1), new ColumnState2(ColumnDefinitions.Whitespace.Description, isVisible: true, width: 0), new ColumnState2(ColumnDefinitions.Whitespace.Value, isVisible: true, width: 0), new ColumnState2(ColumnDefinitions.Whitespace.Location, isVisible: true, width: 0) }; protected override string[] GetFixedColumns() => new[] { ColumnDefinitions.Whitespace.Category, ColumnDefinitions.Whitespace.Description, ColumnDefinitions.Whitespace.Value, ColumnDefinitions.Whitespace.Location }; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.DataProvider; using Microsoft.Internal.VisualStudio.Shell.TableControl; using Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common; using Microsoft.VisualStudio.Shell.TableControl; using Microsoft.VisualStudio.Shell.TableManager; namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Whitespace.ViewModel { internal partial class WhitespaceViewModel : SettingsViewModelBase< WhitespaceSetting, WhitespaceViewModel.SettingsSnapshotFactory, WhitespaceViewModel.SettingsEntriesSnapshot> { public WhitespaceViewModel(ISettingsProvider<WhitespaceSetting> data, IWpfTableControlProvider controlProvider, ITableManagerProvider tableMangerProvider) : base(data, controlProvider, tableMangerProvider) { } public override string Identifier => "Whitespace"; protected override SettingsSnapshotFactory CreateSnapshotFactory(ISettingsProvider<WhitespaceSetting> data) => new(data); protected override IEnumerable<ColumnState2> GetInitialColumnStates() => new[] { new ColumnState2(ColumnDefinitions.Whitespace.Category, isVisible: false, width: 0, groupingPriority: 1), new ColumnState2(ColumnDefinitions.Whitespace.Description, isVisible: true, width: 0), new ColumnState2(ColumnDefinitions.Whitespace.Value, isVisible: true, width: 0), new ColumnState2(ColumnDefinitions.Whitespace.Location, isVisible: true, width: 0) }; protected override string[] GetFixedColumns() => new[] { ColumnDefinitions.Whitespace.Category, ColumnDefinitions.Whitespace.Description, ColumnDefinitions.Whitespace.Value, ColumnDefinitions.Whitespace.Location }; } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/Compilers/Core/Portable/Syntax/SyntaxNodeLocationComparer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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; namespace Microsoft.CodeAnalysis { internal class SyntaxNodeLocationComparer : IComparer<SyntaxNode> { private readonly Compilation _compilation; public SyntaxNodeLocationComparer(Compilation compilation) { _compilation = compilation; } public int Compare(SyntaxNode? x, SyntaxNode? y) { if (x is null) { if (y is null) { return 0; } return -1; } else if (y is null) { return 1; } else { return _compilation.CompareSourceLocations(x, y); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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; namespace Microsoft.CodeAnalysis { internal class SyntaxNodeLocationComparer : IComparer<SyntaxNode> { private readonly Compilation _compilation; public SyntaxNodeLocationComparer(Compilation compilation) { _compilation = compilation; } public int Compare(SyntaxNode? x, SyntaxNode? y) { if (x is null) { if (y is null) { return 0; } return -1; } else if (y is null) { return 1; } else { return _compilation.CompareSourceLocations(x, y); } } } }
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/Features/VisualBasic/Portable/ChangeSignature/UnifiedArgumentSyntax.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.ChangeSignature Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.ChangeSignature Friend Class UnifiedArgumentSyntax Implements IUnifiedArgumentSyntax Private ReadOnly _argument As ArgumentSyntax Private Sub New(argument As ArgumentSyntax) Debug.Assert(argument.IsKind(SyntaxKind.SimpleArgument)) Me._argument = argument End Sub Public Shared Function Create(argument As ArgumentSyntax) As IUnifiedArgumentSyntax Return New UnifiedArgumentSyntax(argument) End Function Private ReadOnly Property IsDefault As Boolean Implements IUnifiedArgumentSyntax.IsDefault Get Return _argument Is Nothing End Get End Property Private ReadOnly Property IsNamed As Boolean Implements IUnifiedArgumentSyntax.IsNamed Get Return _argument.IsNamed End Get End Property Public Shared Widening Operator CType(ByVal unified As UnifiedArgumentSyntax) As ArgumentSyntax Return unified._argument End Operator Public Function GetName() As String Implements IUnifiedArgumentSyntax.GetName Return If(_argument.IsNamed, DirectCast(_argument, SimpleArgumentSyntax).NameColonEquals.Name.Identifier.ToString(), Nothing) End Function Private Function WithName(name As String) As IUnifiedArgumentSyntax Implements IUnifiedArgumentSyntax.WithName Return If(_argument.IsNamed, Create(DirectCast(_argument, SimpleArgumentSyntax).WithNameColonEquals(DirectCast(_argument, SimpleArgumentSyntax).NameColonEquals.WithName(SyntaxFactory.IdentifierName(name)))), Create(SyntaxFactory.SimpleArgument(SyntaxFactory.NameColonEquals(SyntaxFactory.IdentifierName(name)), _argument.GetExpression()))) End Function Public Function WithAdditionalAnnotations(annotation As SyntaxAnnotation) As IUnifiedArgumentSyntax Implements IUnifiedArgumentSyntax.WithAdditionalAnnotations Return New UnifiedArgumentSyntax(_argument.WithAdditionalAnnotations(annotation)) 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.ChangeSignature Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.ChangeSignature Friend Class UnifiedArgumentSyntax Implements IUnifiedArgumentSyntax Private ReadOnly _argument As ArgumentSyntax Private Sub New(argument As ArgumentSyntax) Debug.Assert(argument.IsKind(SyntaxKind.SimpleArgument)) Me._argument = argument End Sub Public Shared Function Create(argument As ArgumentSyntax) As IUnifiedArgumentSyntax Return New UnifiedArgumentSyntax(argument) End Function Private ReadOnly Property IsDefault As Boolean Implements IUnifiedArgumentSyntax.IsDefault Get Return _argument Is Nothing End Get End Property Private ReadOnly Property IsNamed As Boolean Implements IUnifiedArgumentSyntax.IsNamed Get Return _argument.IsNamed End Get End Property Public Shared Widening Operator CType(ByVal unified As UnifiedArgumentSyntax) As ArgumentSyntax Return unified._argument End Operator Public Function GetName() As String Implements IUnifiedArgumentSyntax.GetName Return If(_argument.IsNamed, DirectCast(_argument, SimpleArgumentSyntax).NameColonEquals.Name.Identifier.ToString(), Nothing) End Function Private Function WithName(name As String) As IUnifiedArgumentSyntax Implements IUnifiedArgumentSyntax.WithName Return If(_argument.IsNamed, Create(DirectCast(_argument, SimpleArgumentSyntax).WithNameColonEquals(DirectCast(_argument, SimpleArgumentSyntax).NameColonEquals.WithName(SyntaxFactory.IdentifierName(name)))), Create(SyntaxFactory.SimpleArgument(SyntaxFactory.NameColonEquals(SyntaxFactory.IdentifierName(name)), _argument.GetExpression()))) End Function Public Function WithAdditionalAnnotations(annotation As SyntaxAnnotation) As IUnifiedArgumentSyntax Implements IUnifiedArgumentSyntax.WithAdditionalAnnotations Return New UnifiedArgumentSyntax(_argument.WithAdditionalAnnotations(annotation)) End Function End Class End Namespace
-1
dotnet/roslyn
56,333
Add support for all parenthesized binary additions of interpolated strings
Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
333fred
"2021-09-11T00:35:39Z"
"2021-09-22T20:48:32Z"
1c562662d3da5749587a9f4547fd6353a1d77ca4
b071cda7f8b3fc8da2ead93c851c64a1a20d35a6
Add support for all parenthesized binary additions of interpolated strings. Implements the decision from https://github.com/dotnet/csharplang/issues/5106. Test plan at https://github.com/dotnet/roslyn/issues/51499.
./src/Compilers/CSharp/Test/Symbol/Symbols/ImplicitClassTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class ImplicitClassTests : CSharpTestBase { [Fact] public void ImplicitClassSymbol() { var c = CreateEmptyCompilation(@" namespace N { void Goo() { } } ", new[] { MscorlibRef }); var n = ((NamespaceSymbol)c.Assembly.GlobalNamespace.GetMembers("N").Single()); var implicitClass = ((NamedTypeSymbol)n.GetMembers().Single()); Assert.Equal(0, implicitClass.GetAttributes().Length); Assert.Equal(0, implicitClass.Interfaces().Length); Assert.Equal(c.ObjectType, implicitClass.BaseType()); Assert.Equal(0, implicitClass.Arity); Assert.True(implicitClass.IsImplicitlyDeclared); Assert.Equal(SyntaxKind.NamespaceDeclaration, implicitClass.DeclaringSyntaxReferences.Single().GetSyntax().Kind()); Assert.False(implicitClass.IsSubmissionClass); Assert.False(implicitClass.IsScriptClass); var c2 = CreateCompilationWithMscorlib45("", new[] { c.ToMetadataReference() }); n = ((NamespaceSymbol)c2.GlobalNamespace.GetMembers("N").Single()); implicitClass = ((NamedTypeSymbol)n.GetMembers().Single()); Assert.IsType<CSharp.Symbols.Retargeting.RetargetingNamedTypeSymbol>(implicitClass); Assert.Equal(0, implicitClass.Interfaces().Length); Assert.Equal(c2.ObjectType, implicitClass.BaseType()); } [Fact] public void ScriptClassSymbol() { var c = CreateCompilation(@" base.ToString(); void Goo() { } ", parseOptions: TestOptions.Script); var scriptClass = (NamedTypeSymbol)c.Assembly.GlobalNamespace.GetMember("Script"); Assert.Equal(0, scriptClass.GetAttributes().Length); Assert.Equal(0, scriptClass.Interfaces().Length); Assert.Null(scriptClass.BaseType()); Assert.Equal(0, scriptClass.Arity); Assert.True(scriptClass.IsImplicitlyDeclared); Assert.Equal(SyntaxKind.CompilationUnit, scriptClass.DeclaringSyntaxReferences.Single().GetSyntax().Kind()); Assert.False(scriptClass.IsSubmissionClass); Assert.True(scriptClass.IsScriptClass); var tree = c.SyntaxTrees.Single(); var model = c.GetSemanticModel(tree); IEnumerable<IdentifierNameSyntax> identifiers = tree.GetCompilationUnitRoot().DescendantNodes().OfType<IdentifierNameSyntax>(); var toStringIdentifier = identifiers.Where(node => node.Identifier.ValueText.Equals("ToString")).Single(); Assert.Null(model.GetSymbolInfo(toStringIdentifier).Symbol); } [Fact, WorkItem(531535, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531535")] public void Events() { var c = CreateCompilationWithMscorlib45(@" event System.Action e; ", parseOptions: TestOptions.Script); c.VerifyDiagnostics(); var @event = c.ScriptClass.GetMember<EventSymbol>("e"); Assert.False(@event.TypeWithAnnotations.IsDefault); } [WorkItem(598860, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/598860")] [Fact] public void AliasQualifiedNamespaceName() { var comp = CreateCompilation(@" namespace N::A { void Goo() { } } "); // Used to assert. comp.VerifyDiagnostics( // (2,11): error CS7000: Unexpected use of an aliased name // namespace N::A Diagnostic(ErrorCode.ERR_UnexpectedAliasedName, "N::A"), // (4,10): error CS0116: A namespace does not directly contain members such as fields or methods // void Goo() Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "Goo")); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var namespaceDecl = tree.GetCompilationUnitRoot().DescendantNodes().OfType<NamespaceDeclarationSyntax>().Single(); var methodDecl = tree.GetCompilationUnitRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single(); Assert.Equal("A", model.GetDeclaredSymbol(namespaceDecl).Name); Assert.Equal("Goo", model.GetDeclaredSymbol(methodDecl).Name); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class ImplicitClassTests : CSharpTestBase { [Fact] public void ImplicitClassSymbol() { var c = CreateEmptyCompilation(@" namespace N { void Goo() { } } ", new[] { MscorlibRef }); var n = ((NamespaceSymbol)c.Assembly.GlobalNamespace.GetMembers("N").Single()); var implicitClass = ((NamedTypeSymbol)n.GetMembers().Single()); Assert.Equal(0, implicitClass.GetAttributes().Length); Assert.Equal(0, implicitClass.Interfaces().Length); Assert.Equal(c.ObjectType, implicitClass.BaseType()); Assert.Equal(0, implicitClass.Arity); Assert.True(implicitClass.IsImplicitlyDeclared); Assert.Equal(SyntaxKind.NamespaceDeclaration, implicitClass.DeclaringSyntaxReferences.Single().GetSyntax().Kind()); Assert.False(implicitClass.IsSubmissionClass); Assert.False(implicitClass.IsScriptClass); var c2 = CreateCompilationWithMscorlib45("", new[] { c.ToMetadataReference() }); n = ((NamespaceSymbol)c2.GlobalNamespace.GetMembers("N").Single()); implicitClass = ((NamedTypeSymbol)n.GetMembers().Single()); Assert.IsType<CSharp.Symbols.Retargeting.RetargetingNamedTypeSymbol>(implicitClass); Assert.Equal(0, implicitClass.Interfaces().Length); Assert.Equal(c2.ObjectType, implicitClass.BaseType()); } [Fact] public void ScriptClassSymbol() { var c = CreateCompilation(@" base.ToString(); void Goo() { } ", parseOptions: TestOptions.Script); var scriptClass = (NamedTypeSymbol)c.Assembly.GlobalNamespace.GetMember("Script"); Assert.Equal(0, scriptClass.GetAttributes().Length); Assert.Equal(0, scriptClass.Interfaces().Length); Assert.Null(scriptClass.BaseType()); Assert.Equal(0, scriptClass.Arity); Assert.True(scriptClass.IsImplicitlyDeclared); Assert.Equal(SyntaxKind.CompilationUnit, scriptClass.DeclaringSyntaxReferences.Single().GetSyntax().Kind()); Assert.False(scriptClass.IsSubmissionClass); Assert.True(scriptClass.IsScriptClass); var tree = c.SyntaxTrees.Single(); var model = c.GetSemanticModel(tree); IEnumerable<IdentifierNameSyntax> identifiers = tree.GetCompilationUnitRoot().DescendantNodes().OfType<IdentifierNameSyntax>(); var toStringIdentifier = identifiers.Where(node => node.Identifier.ValueText.Equals("ToString")).Single(); Assert.Null(model.GetSymbolInfo(toStringIdentifier).Symbol); } [Fact, WorkItem(531535, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531535")] public void Events() { var c = CreateCompilationWithMscorlib45(@" event System.Action e; ", parseOptions: TestOptions.Script); c.VerifyDiagnostics(); var @event = c.ScriptClass.GetMember<EventSymbol>("e"); Assert.False(@event.TypeWithAnnotations.IsDefault); } [WorkItem(598860, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/598860")] [Fact] public void AliasQualifiedNamespaceName() { var comp = CreateCompilation(@" namespace N::A { void Goo() { } } "); // Used to assert. comp.VerifyDiagnostics( // (2,11): error CS7000: Unexpected use of an aliased name // namespace N::A Diagnostic(ErrorCode.ERR_UnexpectedAliasedName, "N::A"), // (4,10): error CS0116: A namespace does not directly contain members such as fields or methods // void Goo() Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "Goo")); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var namespaceDecl = tree.GetCompilationUnitRoot().DescendantNodes().OfType<NamespaceDeclarationSyntax>().Single(); var methodDecl = tree.GetCompilationUnitRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single(); Assert.Equal("A", model.GetDeclaredSymbol(namespaceDecl).Name); Assert.Equal("Goo", model.GetDeclaredSymbol(methodDecl).Name); } } }
-1
dotnet/roslyn
56,310
Move semantic classification caching down to Editor layer
CyrusNajmabadi
"2021-09-09T23:15:16Z"
"2021-09-10T19:26:25Z"
6e123012d868c56aba8acabfe1ccad1bf8f20b04
7af13b6e3867198cd59c566a905b332888ea1dec
Move semantic classification caching down to Editor layer.
./src/EditorFeatures/Core/Implementation/Classification/SemanticClassificationUtilities.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editor.Tagging; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Tagging; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.Classification { internal static class SemanticClassificationUtilities { public static async Task ProduceTagsAsync( TaggerContext<IClassificationTag> context, DocumentSnapshotSpan spanToTag, IClassificationService classificationService, ClassificationTypeMap typeMap) { var document = spanToTag.Document; if (document == null) return; // Don't block getting classifications on building the full compilation. This may take a significant amount // of time and can cause a very latency sensitive operation (copying) to block the user while we wait on this // work to happen. // // It's also a better experience to get classifications to the user faster versus waiting a potentially // large amount of time waiting for all the compilation information to be built. For example, we can // classify types that we've parsed in other files, or partially loaded from metadata, even if we're still // parsing/loading. For cross language projects, this also produces semantic classifications more quickly // as we do not have to wait on skeletons to be built. document = document.WithFrozenPartialSemantics(context.CancellationToken); spanToTag = new DocumentSnapshotSpan(document, spanToTag.SnapshotSpan); var classified = await TryClassifyContainingMemberSpanAsync( context, spanToTag, classificationService, typeMap).ConfigureAwait(false); if (classified) { return; } // We weren't able to use our specialized codepaths for semantic classifying. // Fall back to classifying the full span that was asked for. await ClassifySpansAsync( context, spanToTag, classificationService, typeMap).ConfigureAwait(false); } private static async Task<bool> TryClassifyContainingMemberSpanAsync( TaggerContext<IClassificationTag> context, DocumentSnapshotSpan spanToTag, IClassificationService classificationService, ClassificationTypeMap typeMap) { var range = context.TextChangeRange; if (range == null) { // There was no text change range, we can't just reclassify a member body. return false; } // there was top level edit, check whether that edit updated top level element var document = spanToTag.Document; if (!document.SupportsSyntaxTree) { return false; } var cancellationToken = context.CancellationToken; var lastSemanticVersion = (VersionStamp?)context.State; if (lastSemanticVersion != null) { var currentSemanticVersion = await document.Project.GetDependentSemanticVersionAsync(cancellationToken).ConfigureAwait(false); if (lastSemanticVersion.Value != currentSemanticVersion) { // A top level change was made. We can't perform this optimization. return false; } } var service = document.GetLanguageService<ISyntaxFactsService>(); // perf optimization. Check whether all edits since the last update has happened within // a member. If it did, it will find the member that contains the changes and only refresh // that member. If possible, try to get a speculative binder to make things even cheaper. var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var changedSpan = new TextSpan(range.Value.Span.Start, range.Value.NewLength); var member = service.GetContainingMemberDeclaration(root, changedSpan.Start); if (member == null || !member.FullSpan.Contains(changedSpan)) { // The edit was not fully contained in a member. Reclassify everything. return false; } var subTextSpan = service.GetMemberBodySpanForSpeculativeBinding(member); if (subTextSpan.IsEmpty) { // Wasn't a member we could reclassify independently. return false; } var subSpan = subTextSpan.Contains(changedSpan) ? subTextSpan.ToSpan() : member.FullSpan.ToSpan(); var subSpanToTag = new DocumentSnapshotSpan(spanToTag.Document, new SnapshotSpan(spanToTag.SnapshotSpan.Snapshot, subSpan)); // re-classify only the member we're inside. await ClassifySpansAsync( context, subSpanToTag, classificationService, typeMap).ConfigureAwait(false); return true; } private static async Task ClassifySpansAsync( TaggerContext<IClassificationTag> context, DocumentSnapshotSpan spanToTag, IClassificationService classificationService, ClassificationTypeMap typeMap) { try { var document = spanToTag.Document; var snapshotSpan = spanToTag.SnapshotSpan; var snapshot = snapshotSpan.Snapshot; var cancellationToken = context.CancellationToken; using (Logger.LogBlock(FunctionId.Tagger_SemanticClassification_TagProducer_ProduceTags, cancellationToken)) { using var _ = ArrayBuilder<ClassifiedSpan>.GetInstance(out var classifiedSpans); await AddSemanticClassificationsAsync( document, snapshotSpan.Span.ToTextSpan(), classificationService, classifiedSpans, cancellationToken: cancellationToken).ConfigureAwait(false); foreach (var span in classifiedSpans) context.AddTag(ClassificationUtilities.Convert(typeMap, snapshotSpan.Snapshot, span)); var version = await document.Project.GetDependentSemanticVersionAsync(cancellationToken).ConfigureAwait(false); // Let the context know that this was the span we actually tried to tag. context.SetSpansTagged(SpecializedCollections.SingletonEnumerable(spanToTag)); context.State = version; } } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } private static async Task AddSemanticClassificationsAsync( Document document, TextSpan textSpan, IClassificationService classificationService, ArrayBuilder<ClassifiedSpan> classifiedSpans, CancellationToken cancellationToken) { var workspaceStatusService = document.Project.Solution.Workspace.Services.GetRequiredService<IWorkspaceStatusService>(); // Importantly, we do not await/wait on the fullyLoadedStateTask. We do not want to ever be waiting on work // that may end up touching the UI thread (As we can deadlock if GetTagsSynchronous waits on us). Instead, // we only check if the Task is completed. Prior to that we will assume we are still loading. Once this // task is completed, we know that the WaitUntilFullyLoadedAsync call will have actually finished and we're // fully loaded. var isFullyLoadedTask = workspaceStatusService.IsFullyLoadedAsync(cancellationToken); var isFullyLoaded = isFullyLoadedTask.IsCompleted && isFullyLoadedTask.GetAwaiter().GetResult(); // If we're not fully loaded try to read from the cache instead so that classifications appear up to date. // New code will not be semantically classified, but will eventually when the project fully loads. if (await TryAddSemanticClassificationsFromCacheAsync(document, textSpan, classifiedSpans, isFullyLoaded, cancellationToken).ConfigureAwait(false)) return; await classificationService.AddSemanticClassificationsAsync( document, textSpan, classifiedSpans, cancellationToken).ConfigureAwait(false); } private static async Task<bool> TryAddSemanticClassificationsFromCacheAsync( Document document, TextSpan textSpan, ArrayBuilder<ClassifiedSpan> classifiedSpans, bool isFullyLoaded, CancellationToken cancellationToken) { // Don't use the cache if we're fully loaded. We should just compute values normally. if (isFullyLoaded) return false; var semanticCacheService = document.Project.Solution.Workspace.Services.GetService<ISemanticClassificationCacheService>(); if (semanticCacheService == null) return false; var checksums = await document.State.GetStateChecksumsAsync(cancellationToken).ConfigureAwait(false); var checksum = checksums.Text; var result = await semanticCacheService.GetCachedSemanticClassificationsAsync( SemanticClassificationCacheUtilities.GetDocumentKeyForCaching(document), textSpan, checksum, cancellationToken).ConfigureAwait(false); if (result.IsDefault) return false; classifiedSpans.AddRange(result); return true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editor.Tagging; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Tagging; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.Classification { internal static class SemanticClassificationUtilities { public static async Task ProduceTagsAsync( TaggerContext<IClassificationTag> context, DocumentSnapshotSpan spanToTag, IClassificationService classificationService, ClassificationTypeMap typeMap) { var document = spanToTag.Document; if (document == null) return; // Don't block getting classifications on building the full compilation. This may take a significant amount // of time and can cause a very latency sensitive operation (copying) to block the user while we wait on this // work to happen. // // It's also a better experience to get classifications to the user faster versus waiting a potentially // large amount of time waiting for all the compilation information to be built. For example, we can // classify types that we've parsed in other files, or partially loaded from metadata, even if we're still // parsing/loading. For cross language projects, this also produces semantic classifications more quickly // as we do not have to wait on skeletons to be built. document = document.WithFrozenPartialSemantics(context.CancellationToken); spanToTag = new DocumentSnapshotSpan(document, spanToTag.SnapshotSpan); var classified = await TryClassifyContainingMemberSpanAsync( context, spanToTag, classificationService, typeMap).ConfigureAwait(false); if (classified) { return; } // We weren't able to use our specialized codepaths for semantic classifying. // Fall back to classifying the full span that was asked for. await ClassifySpansAsync( context, spanToTag, classificationService, typeMap).ConfigureAwait(false); } private static async Task<bool> TryClassifyContainingMemberSpanAsync( TaggerContext<IClassificationTag> context, DocumentSnapshotSpan spanToTag, IClassificationService classificationService, ClassificationTypeMap typeMap) { var range = context.TextChangeRange; if (range == null) { // There was no text change range, we can't just reclassify a member body. return false; } // there was top level edit, check whether that edit updated top level element var document = spanToTag.Document; if (!document.SupportsSyntaxTree) { return false; } var cancellationToken = context.CancellationToken; var lastSemanticVersion = (VersionStamp?)context.State; if (lastSemanticVersion != null) { var currentSemanticVersion = await document.Project.GetDependentSemanticVersionAsync(cancellationToken).ConfigureAwait(false); if (lastSemanticVersion.Value != currentSemanticVersion) { // A top level change was made. We can't perform this optimization. return false; } } var service = document.GetLanguageService<ISyntaxFactsService>(); // perf optimization. Check whether all edits since the last update has happened within // a member. If it did, it will find the member that contains the changes and only refresh // that member. If possible, try to get a speculative binder to make things even cheaper. var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var changedSpan = new TextSpan(range.Value.Span.Start, range.Value.NewLength); var member = service.GetContainingMemberDeclaration(root, changedSpan.Start); if (member == null || !member.FullSpan.Contains(changedSpan)) { // The edit was not fully contained in a member. Reclassify everything. return false; } var subTextSpan = service.GetMemberBodySpanForSpeculativeBinding(member); if (subTextSpan.IsEmpty) { // Wasn't a member we could reclassify independently. return false; } var subSpan = subTextSpan.Contains(changedSpan) ? subTextSpan.ToSpan() : member.FullSpan.ToSpan(); var subSpanToTag = new DocumentSnapshotSpan(spanToTag.Document, new SnapshotSpan(spanToTag.SnapshotSpan.Snapshot, subSpan)); // re-classify only the member we're inside. await ClassifySpansAsync( context, subSpanToTag, classificationService, typeMap).ConfigureAwait(false); return true; } private static async Task ClassifySpansAsync( TaggerContext<IClassificationTag> context, DocumentSnapshotSpan spanToTag, IClassificationService classificationService, ClassificationTypeMap typeMap) { try { var document = spanToTag.Document; var snapshotSpan = spanToTag.SnapshotSpan; var snapshot = snapshotSpan.Snapshot; var cancellationToken = context.CancellationToken; using (Logger.LogBlock(FunctionId.Tagger_SemanticClassification_TagProducer_ProduceTags, cancellationToken)) { using var _ = ArrayBuilder<ClassifiedSpan>.GetInstance(out var classifiedSpans); await AddSemanticClassificationsAsync( document, snapshotSpan.Span.ToTextSpan(), classificationService, classifiedSpans, cancellationToken: cancellationToken).ConfigureAwait(false); foreach (var span in classifiedSpans) context.AddTag(ClassificationUtilities.Convert(typeMap, snapshotSpan.Snapshot, span)); var version = await document.Project.GetDependentSemanticVersionAsync(cancellationToken).ConfigureAwait(false); // Let the context know that this was the span we actually tried to tag. context.SetSpansTagged(SpecializedCollections.SingletonEnumerable(spanToTag)); context.State = version; } } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } private static async Task AddSemanticClassificationsAsync( Document document, TextSpan textSpan, IClassificationService classificationService, ArrayBuilder<ClassifiedSpan> classifiedSpans, CancellationToken cancellationToken) { var workspaceStatusService = document.Project.Solution.Workspace.Services.GetRequiredService<IWorkspaceStatusService>(); // Importantly, we do not await/wait on the fullyLoadedStateTask. We do not want to ever be waiting on work // that may end up touching the UI thread (As we can deadlock if GetTagsSynchronous waits on us). Instead, // we only check if the Task is completed. Prior to that we will assume we are still loading. Once this // task is completed, we know that the WaitUntilFullyLoadedAsync call will have actually finished and we're // fully loaded. var isFullyLoadedTask = workspaceStatusService.IsFullyLoadedAsync(cancellationToken); var isFullyLoaded = isFullyLoadedTask.IsCompleted && isFullyLoadedTask.GetAwaiter().GetResult(); // If we're not fully loaded try to read from the cache instead so that classifications appear up to date. // New code will not be semantically classified, but will eventually when the project fully loads. if (await TryAddSemanticClassificationsFromCacheAsync(document, textSpan, classifiedSpans, isFullyLoaded, cancellationToken).ConfigureAwait(false)) return; await classificationService.AddSemanticClassificationsAsync( document, textSpan, classifiedSpans, cancellationToken).ConfigureAwait(false); } private static async Task<bool> TryAddSemanticClassificationsFromCacheAsync( Document document, TextSpan textSpan, ArrayBuilder<ClassifiedSpan> classifiedSpans, bool isFullyLoaded, CancellationToken cancellationToken) { // Don't use the cache if we're fully loaded. We should just compute values normally. if (isFullyLoaded) return false; var semanticCacheService = document.Project.Solution.Workspace.Services.GetService<ISemanticClassificationCacheService>(); if (semanticCacheService == null) return false; var result = await semanticCacheService.GetCachedSemanticClassificationsAsync( document, textSpan, cancellationToken).ConfigureAwait(false); if (result.IsDefault) return false; classifiedSpans.AddRange(result); return true; } } }
1
dotnet/roslyn
56,310
Move semantic classification caching down to Editor layer
CyrusNajmabadi
"2021-09-09T23:15:16Z"
"2021-09-10T19:26:25Z"
6e123012d868c56aba8acabfe1ccad1bf8f20b04
7af13b6e3867198cd59c566a905b332888ea1dec
Move semantic classification caching down to Editor layer.
./src/Workspaces/Core/Portable/Classification/ISemanticClassificationCacheService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PersistentStorage; using Microsoft.CodeAnalysis.Serialization; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Classification { /// <summary> /// Service that can retrieve semantic classifications for a document cached during a previous session. This is /// intended to help populate semantic classifications for a host during the time while a solution is loading and /// semantics may be incomplete or unavailable. /// </summary> internal interface ISemanticClassificationCacheService : IWorkspaceService { /// <summary> /// Tries to get cached semantic classifications for the specified document and the specified <paramref /// name="textSpan"/>. Will return a <c>default</c> array not able to. An empty array indicates that there /// were cached classifications, but none that intersected the provided <paramref name="textSpan"/>. /// </summary> /// <param name="checksum">Pass in <see cref="DocumentStateChecksums.Text"/>. This will ensure that the cached /// classifications are only returned if they match the content the file currently has.</param> Task<ImmutableArray<ClassifiedSpan>> GetCachedSemanticClassificationsAsync( DocumentKey documentKey, TextSpan textSpan, Checksum checksum, CancellationToken cancellationToken); } [ExportWorkspaceService(typeof(ISemanticClassificationCacheService)), Shared] internal class DefaultSemanticClassificationCacheService : ISemanticClassificationCacheService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public DefaultSemanticClassificationCacheService() { } public Task<ImmutableArray<ClassifiedSpan>> GetCachedSemanticClassificationsAsync(DocumentKey documentKey, TextSpan textSpan, Checksum checksum, CancellationToken cancellationToken) => SpecializedTasks.Default<ImmutableArray<ClassifiedSpan>>(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Classification { /// <summary> /// Service that can retrieve semantic classifications for a document cached during a previous session. This is /// intended to help populate semantic classifications for a host during the time while a solution is loading and /// semantics may be incomplete or unavailable. /// </summary> internal interface ISemanticClassificationCacheService : IWorkspaceService { /// <summary> /// Tries to get cached semantic classifications for the specified document and the specified <paramref /// name="textSpan"/>. Will return a <c>default</c> array not able to. An empty array indicates that there /// were cached classifications, but none that intersected the provided <paramref name="textSpan"/>. /// </summary> Task<ImmutableArray<ClassifiedSpan>> GetCachedSemanticClassificationsAsync( Document document, TextSpan textSpan, CancellationToken cancellationToken); } [ExportWorkspaceService(typeof(ISemanticClassificationCacheService)), Shared] internal class DefaultSemanticClassificationCacheService : ISemanticClassificationCacheService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public DefaultSemanticClassificationCacheService() { } public Task<ImmutableArray<ClassifiedSpan>> GetCachedSemanticClassificationsAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken) => SpecializedTasks.Default<ImmutableArray<ClassifiedSpan>>(); } }
1
dotnet/roslyn
56,310
Move semantic classification caching down to Editor layer
CyrusNajmabadi
"2021-09-09T23:15:16Z"
"2021-09-10T19:26:25Z"
6e123012d868c56aba8acabfe1ccad1bf8f20b04
7af13b6e3867198cd59c566a905b332888ea1dec
Move semantic classification caching down to Editor layer.
./src/Workspaces/Remote/ServiceHub/Services/SemanticClassificationCache/RemoteSemanticClassificationCacheService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.Editor.Implementation.Classification; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.PersistentStorage; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Storage; using Microsoft.CodeAnalysis.Text; using Microsoft.ServiceHub.Framework; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Remote { internal sealed class RemoteSemanticClassificationCacheService : BrokeredServiceBase, IRemoteSemanticClassificationCacheService { internal sealed class Factory : FactoryBase<IRemoteSemanticClassificationCacheService> { protected override IRemoteSemanticClassificationCacheService CreateService(in ServiceConstructionArguments arguments) => new RemoteSemanticClassificationCacheService(arguments); } public RemoteSemanticClassificationCacheService(in ServiceConstructionArguments arguments) : base(arguments) { } /// <summary> /// Key we use to look this up in the persistence store for a particular document. /// </summary> private const string PersistenceName = "<ClassifiedSpans>"; /// <summary> /// Our current persistence version. If we ever change the on-disk format, this should be changed so that we /// skip over persisted data that we cannot read. /// </summary> private const int ClassificationFormat = 3; private const int MaxCachedDocumentCount = 8; /// <summary> /// Cache of the previously requested classified spans for a particular document. We use this so that during /// loading, if we're asking about the same documents multiple times by the classification service, we can just /// return what we have already loaded and not go back to the persistence store to read/decode. /// <para/> /// This can be read and updated from different threads. To keep things safe, we use thsi object itself /// as the lock that is taken to serialize access. /// </summary> private readonly LinkedList<(DocumentId id, Checksum checksum, ImmutableArray<ClassifiedSpan> classifiedSpans)> _cachedData = new(); private static async Task<Checksum> GetChecksumAsync(Document document, CancellationToken cancellationToken) { // We only checksum off of the contents of the file. During load, we can't really compute any other // information since we don't necessarily know about other files, metadata, or dependencies. So during // load, we allow for the previous semantic classifications to be used as long as the file contents match. var checksums = await document.State.GetStateChecksumsAsync(cancellationToken).ConfigureAwait(false); var textChecksum = checksums.Text; return textChecksum; } public ValueTask CacheSemanticClassificationsAsync( PinnedSolutionInfo solutionInfo, DocumentId documentId, CancellationToken cancellationToken) { return RunServiceAsync(async cancellationToken => { // We only get called to cache classifications once we're fully loaded. At that point there's no need // for us to keep around any of the data we cached in-memory during the time the solution was loading. lock (_cachedData) _cachedData.Clear(); var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false); var document = solution.GetRequiredDocument(documentId); await CacheSemanticClassificationsAsync(document, cancellationToken).ConfigureAwait(false); }, cancellationToken); } private static async Task CacheSemanticClassificationsAsync(Document document, CancellationToken cancellationToken) { var solution = document.Project.Solution; var workspace = solution.Workspace; var persistenceService = workspace.Services.GetService<IPersistentStorageService>() as IChecksummedPersistentStorageService; if (persistenceService == null) return; var storage = await persistenceService.GetStorageAsync(SolutionKey.ToSolutionKey(solution), checkBranchId: true, cancellationToken).ConfigureAwait(false); await using var _1 = storage.ConfigureAwait(false); if (storage == null) return; var classificationService = document.GetLanguageService<IClassificationService>(); if (classificationService == null) return; // Very intentionally do our lookup with a special document key. This doc key stores info independent of // project config. So we can still lookup data regardless of things like if the project is in DEBUG or // RELEASE mode. var documentKey = SemanticClassificationCacheUtilities.GetDocumentKeyForCaching(document); // Don't need to do anything if the information we've persisted matches the checksum of this doc. var checksum = await GetChecksumAsync(document, cancellationToken).ConfigureAwait(false); var matches = await storage.ChecksumMatchesAsync(documentKey, PersistenceName, checksum, cancellationToken).ConfigureAwait(false); if (matches) return; using var _2 = ArrayBuilder<ClassifiedSpan>.GetInstance(out var classifiedSpans); // Compute classifications for the full span. var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); await classificationService.AddSemanticClassificationsAsync(document, new TextSpan(0, text.Length), classifiedSpans, cancellationToken).ConfigureAwait(false); using var stream = SerializableBytes.CreateWritableStream(); using (var writer = new ObjectWriter(stream, leaveOpen: true, cancellationToken)) { WriteTo(classifiedSpans, writer); } stream.Position = 0; await storage.WriteStreamAsync(documentKey, PersistenceName, stream, checksum, cancellationToken).ConfigureAwait(false); } private static void WriteTo(ArrayBuilder<ClassifiedSpan> classifiedSpans, ObjectWriter writer) { writer.WriteInt32(ClassificationFormat); // First, look through all the spans and determine which classification types are used. For efficiency, // we'll emit the unique types up front and then only refer to them by index for all the actual classified // spans we emit. using var _1 = ArrayBuilder<string>.GetInstance(out var classificationTypes); using var _2 = PooledDictionary<string, int>.GetInstance(out var seenClassificationTypes); foreach (var classifiedSpan in classifiedSpans) { var classificationType = classifiedSpan.ClassificationType; if (!seenClassificationTypes.ContainsKey(classificationType)) { seenClassificationTypes.Add(classificationType, classificationTypes.Count); classificationTypes.Add(classificationType); } } writer.WriteInt32(classificationTypes.Count); foreach (var type in classificationTypes) writer.WriteString(type); // Now emit each classified span as a triple of it's start, length, type. // // In general, the latter two will all be a single byte as tokens tend to be short and we don't have many // classification types. // // We do need to store the start (as opposed to a delta) as we may have multiple items starting at the same // position and we cannot encode a negative delta. writer.WriteInt32(classifiedSpans.Count); foreach (var classifiedSpan in classifiedSpans) { checked { writer.WriteInt32(classifiedSpan.TextSpan.Start); writer.WriteCompressedUInt((uint)classifiedSpan.TextSpan.Length); writer.WriteCompressedUInt((uint)seenClassificationTypes[classifiedSpan.ClassificationType]); } } } public ValueTask<SerializableClassifiedSpans?> GetCachedSemanticClassificationsAsync( DocumentKey documentKey, TextSpan textSpan, Checksum checksum, CancellationToken cancellationToken) { return RunServiceAsync(async cancellationToken => { var classifiedSpans = await TryGetOrReadCachedSemanticClassificationsAsync( documentKey, checksum, cancellationToken).ConfigureAwait(false); if (classifiedSpans.IsDefault) return null; return SerializableClassifiedSpans.Dehydrate(classifiedSpans.WhereAsArray(c => c.TextSpan.IntersectsWith(textSpan))); }, cancellationToken); } private async Task<ImmutableArray<ClassifiedSpan>> TryGetOrReadCachedSemanticClassificationsAsync( DocumentKey documentKey, Checksum checksum, CancellationToken cancellationToken) { // See if we've loaded this into memory first. if (TryGetFromInMemoryCache(documentKey, checksum, out var classifiedSpans)) return classifiedSpans; // Otherwise, attempt to read in classifications from persistence store. classifiedSpans = await TryReadCachedSemanticClassificationsAsync( documentKey, checksum, cancellationToken).ConfigureAwait(false); if (classifiedSpans.IsDefault) return default; UpdateInMemoryCache(documentKey, checksum, classifiedSpans); return classifiedSpans; } private bool TryGetFromInMemoryCache(DocumentKey documentKey, Checksum checksum, out ImmutableArray<ClassifiedSpan> classifiedSpans) { lock (_cachedData) { var data = _cachedData.FirstOrNull(d => d.id == documentKey.Id && d.checksum == checksum); if (data != null) { classifiedSpans = data.Value.classifiedSpans; return true; } } classifiedSpans = default; return false; } private void UpdateInMemoryCache( DocumentKey documentKey, Checksum checksum, ImmutableArray<ClassifiedSpan> classifiedSpans) { lock (_cachedData) { // First, remove any existing info for this doc. for (var currentNode = _cachedData.First; currentNode != null; currentNode = currentNode.Next) { if (currentNode.Value.id == documentKey.Id) { _cachedData.Remove(currentNode); break; } } // Then place the cached information for this doc at the end. _cachedData.AddLast((documentKey.Id, checksum, classifiedSpans)); // And ensure we don't cache too many docs. if (_cachedData.Count > MaxCachedDocumentCount) _cachedData.RemoveFirst(); } } private async Task<ImmutableArray<ClassifiedSpan>> TryReadCachedSemanticClassificationsAsync( DocumentKey documentKey, Checksum checksum, CancellationToken cancellationToken) { var workspace = GetWorkspace(); if (workspace.Services.GetService<IPersistentStorageService>() is not IChecksummedPersistentStorageService persistenceService) return default; var storage = await persistenceService.GetStorageAsync(documentKey.Project.Solution, checkBranchId: false, cancellationToken).ConfigureAwait(false); await using var _ = storage.ConfigureAwait(false); if (storage == null) return default; using var stream = await storage.ReadStreamAsync(documentKey, PersistenceName, checksum, cancellationToken).ConfigureAwait(false); using var reader = ObjectReader.TryGetReader(stream, cancellationToken: cancellationToken); if (reader == null) return default; return Read(reader); } private static ImmutableArray<ClassifiedSpan> Read(ObjectReader reader) { try { // if the format doesn't match, we def can't read this. if (reader.ReadInt32() != ClassificationFormat) return default; // For space efficiency, the unique classification types are emitted in one array up front, and then the // specific classification type is referred to by index when emitting the individual spans. var classificationTypesCount = reader.ReadInt32(); using var _1 = ArrayBuilder<string>.GetInstance(classificationTypesCount, out var classificationTypes); for (var i = 0; i < classificationTypesCount; i++) classificationTypes.Add(reader.ReadString()); var classifiedSpanCount = reader.ReadInt32(); using var _2 = ArrayBuilder<ClassifiedSpan>.GetInstance(classifiedSpanCount, out var classifiedSpans); for (var i = 0; i < classifiedSpanCount; i++) { checked { var start = reader.ReadInt32(); var length = (int)reader.ReadCompressedUInt(); var typeIndex = (int)reader.ReadCompressedUInt(); classifiedSpans.Add(new ClassifiedSpan(classificationTypes[typeIndex], new TextSpan(start, length))); } } return classifiedSpans.ToImmutable(); } catch { // We're reading and interpreting arbitrary data from disk. This may be invalid for any reason. Internal.Log.Logger.Log(FunctionId.RemoteSemanticClassificationCacheService_ExceptionInCacheRead); return default; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.PersistentStorage; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.SemanticClassificationCache; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Storage; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Remote { internal sealed class RemoteSemanticClassificationCacheService : BrokeredServiceBase, IRemoteSemanticClassificationCacheService { internal sealed class Factory : FactoryBase<IRemoteSemanticClassificationCacheService> { protected override IRemoteSemanticClassificationCacheService CreateService(in ServiceConstructionArguments arguments) => new RemoteSemanticClassificationCacheService(arguments); } public RemoteSemanticClassificationCacheService(in ServiceConstructionArguments arguments) : base(arguments) { } /// <summary> /// Key we use to look this up in the persistence store for a particular document. /// </summary> private const string PersistenceName = "<ClassifiedSpans>"; /// <summary> /// Our current persistence version. If we ever change the on-disk format, this should be changed so that we /// skip over persisted data that we cannot read. /// </summary> private const int ClassificationFormat = 3; private const int MaxCachedDocumentCount = 8; /// <summary> /// Cache of the previously requested classified spans for a particular document. We use this so that during /// loading, if we're asking about the same documents multiple times by the classification service, we can just /// return what we have already loaded and not go back to the persistence store to read/decode. /// <para/> /// This can be read and updated from different threads. To keep things safe, we use thsi object itself /// as the lock that is taken to serialize access. /// </summary> private readonly LinkedList<(DocumentId id, Checksum checksum, ImmutableArray<ClassifiedSpan> classifiedSpans)> _cachedData = new(); public ValueTask CacheSemanticClassificationsAsync( PinnedSolutionInfo solutionInfo, DocumentId documentId, CancellationToken cancellationToken) { return RunServiceAsync(async cancellationToken => { // We only get called to cache classifications once we're fully loaded. At that point there's no need // for us to keep around any of the data we cached in-memory during the time the solution was loading. lock (_cachedData) _cachedData.Clear(); var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false); var document = solution.GetRequiredDocument(documentId); await CacheSemanticClassificationsAsync(document, cancellationToken).ConfigureAwait(false); }, cancellationToken); } private static async Task CacheSemanticClassificationsAsync(Document document, CancellationToken cancellationToken) { var solution = document.Project.Solution; var workspace = solution.Workspace; var persistenceService = workspace.Services.GetService<IPersistentStorageService>() as IChecksummedPersistentStorageService; if (persistenceService == null) return; var storage = await persistenceService.GetStorageAsync(SolutionKey.ToSolutionKey(solution), checkBranchId: true, cancellationToken).ConfigureAwait(false); await using var _1 = storage.ConfigureAwait(false); if (storage == null) return; var classificationService = document.GetLanguageService<IClassificationService>(); if (classificationService == null) return; // Very intentionally do our lookup with a special document key. This doc key stores info independent of // project config. So we can still lookup data regardless of things like if the project is in DEBUG or // RELEASE mode. var (documentKey, checksum) = await SemanticClassificationCacheUtilities.GetDocumentKeyAndChecksumAsync( document, cancellationToken).ConfigureAwait(false); var matches = await storage.ChecksumMatchesAsync(documentKey, PersistenceName, checksum, cancellationToken).ConfigureAwait(false); if (matches) return; using var _2 = ArrayBuilder<ClassifiedSpan>.GetInstance(out var classifiedSpans); // Compute classifications for the full span. var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); await classificationService.AddSemanticClassificationsAsync(document, new TextSpan(0, text.Length), classifiedSpans, cancellationToken).ConfigureAwait(false); using var stream = SerializableBytes.CreateWritableStream(); using (var writer = new ObjectWriter(stream, leaveOpen: true, cancellationToken)) { WriteTo(classifiedSpans, writer); } stream.Position = 0; await storage.WriteStreamAsync(documentKey, PersistenceName, stream, checksum, cancellationToken).ConfigureAwait(false); } private static void WriteTo(ArrayBuilder<ClassifiedSpan> classifiedSpans, ObjectWriter writer) { writer.WriteInt32(ClassificationFormat); // First, look through all the spans and determine which classification types are used. For efficiency, // we'll emit the unique types up front and then only refer to them by index for all the actual classified // spans we emit. using var _1 = ArrayBuilder<string>.GetInstance(out var classificationTypes); using var _2 = PooledDictionary<string, int>.GetInstance(out var seenClassificationTypes); foreach (var classifiedSpan in classifiedSpans) { var classificationType = classifiedSpan.ClassificationType; if (!seenClassificationTypes.ContainsKey(classificationType)) { seenClassificationTypes.Add(classificationType, classificationTypes.Count); classificationTypes.Add(classificationType); } } writer.WriteInt32(classificationTypes.Count); foreach (var type in classificationTypes) writer.WriteString(type); // Now emit each classified span as a triple of it's start, length, type. // // In general, the latter two will all be a single byte as tokens tend to be short and we don't have many // classification types. // // We do need to store the start (as opposed to a delta) as we may have multiple items starting at the same // position and we cannot encode a negative delta. writer.WriteInt32(classifiedSpans.Count); foreach (var classifiedSpan in classifiedSpans) { checked { writer.WriteInt32(classifiedSpan.TextSpan.Start); writer.WriteCompressedUInt((uint)classifiedSpan.TextSpan.Length); writer.WriteCompressedUInt((uint)seenClassificationTypes[classifiedSpan.ClassificationType]); } } } public ValueTask<SerializableClassifiedSpans?> GetCachedSemanticClassificationsAsync( DocumentKey documentKey, TextSpan textSpan, Checksum checksum, CancellationToken cancellationToken) { return RunServiceAsync(async cancellationToken => { var classifiedSpans = await TryGetOrReadCachedSemanticClassificationsAsync( documentKey, checksum, cancellationToken).ConfigureAwait(false); if (classifiedSpans.IsDefault) return null; return SerializableClassifiedSpans.Dehydrate(classifiedSpans.WhereAsArray(c => c.TextSpan.IntersectsWith(textSpan))); }, cancellationToken); } private async Task<ImmutableArray<ClassifiedSpan>> TryGetOrReadCachedSemanticClassificationsAsync( DocumentKey documentKey, Checksum checksum, CancellationToken cancellationToken) { // See if we've loaded this into memory first. if (TryGetFromInMemoryCache(documentKey, checksum, out var classifiedSpans)) return classifiedSpans; // Otherwise, attempt to read in classifications from persistence store. classifiedSpans = await TryReadCachedSemanticClassificationsAsync( documentKey, checksum, cancellationToken).ConfigureAwait(false); if (classifiedSpans.IsDefault) return default; UpdateInMemoryCache(documentKey, checksum, classifiedSpans); return classifiedSpans; } private bool TryGetFromInMemoryCache(DocumentKey documentKey, Checksum checksum, out ImmutableArray<ClassifiedSpan> classifiedSpans) { lock (_cachedData) { var data = _cachedData.FirstOrNull(d => d.id == documentKey.Id && d.checksum == checksum); if (data != null) { classifiedSpans = data.Value.classifiedSpans; return true; } } classifiedSpans = default; return false; } private void UpdateInMemoryCache( DocumentKey documentKey, Checksum checksum, ImmutableArray<ClassifiedSpan> classifiedSpans) { lock (_cachedData) { // First, remove any existing info for this doc. for (var currentNode = _cachedData.First; currentNode != null; currentNode = currentNode.Next) { if (currentNode.Value.id == documentKey.Id) { _cachedData.Remove(currentNode); break; } } // Then place the cached information for this doc at the end. _cachedData.AddLast((documentKey.Id, checksum, classifiedSpans)); // And ensure we don't cache too many docs. if (_cachedData.Count > MaxCachedDocumentCount) _cachedData.RemoveFirst(); } } private async Task<ImmutableArray<ClassifiedSpan>> TryReadCachedSemanticClassificationsAsync( DocumentKey documentKey, Checksum checksum, CancellationToken cancellationToken) { var workspace = GetWorkspace(); if (workspace.Services.GetService<IPersistentStorageService>() is not IChecksummedPersistentStorageService persistenceService) return default; var storage = await persistenceService.GetStorageAsync(documentKey.Project.Solution, checkBranchId: false, cancellationToken).ConfigureAwait(false); await using var _ = storage.ConfigureAwait(false); if (storage == null) return default; using var stream = await storage.ReadStreamAsync(documentKey, PersistenceName, checksum, cancellationToken).ConfigureAwait(false); using var reader = ObjectReader.TryGetReader(stream, cancellationToken: cancellationToken); if (reader == null) return default; return Read(reader); } private static ImmutableArray<ClassifiedSpan> Read(ObjectReader reader) { try { // if the format doesn't match, we def can't read this. if (reader.ReadInt32() != ClassificationFormat) return default; // For space efficiency, the unique classification types are emitted in one array up front, and then the // specific classification type is referred to by index when emitting the individual spans. var classificationTypesCount = reader.ReadInt32(); using var _1 = ArrayBuilder<string>.GetInstance(classificationTypesCount, out var classificationTypes); for (var i = 0; i < classificationTypesCount; i++) classificationTypes.Add(reader.ReadString()); var classifiedSpanCount = reader.ReadInt32(); using var _2 = ArrayBuilder<ClassifiedSpan>.GetInstance(classifiedSpanCount, out var classifiedSpans); for (var i = 0; i < classifiedSpanCount; i++) { checked { var start = reader.ReadInt32(); var length = (int)reader.ReadCompressedUInt(); var typeIndex = (int)reader.ReadCompressedUInt(); classifiedSpans.Add(new ClassifiedSpan(classificationTypes[typeIndex], new TextSpan(start, length))); } } return classifiedSpans.ToImmutable(); } catch { // We're reading and interpreting arbitrary data from disk. This may be invalid for any reason. Internal.Log.Logger.Log(FunctionId.RemoteSemanticClassificationCacheService_ExceptionInCacheRead); return default; } } } }
1
dotnet/roslyn
56,310
Move semantic classification caching down to Editor layer
CyrusNajmabadi
"2021-09-09T23:15:16Z"
"2021-09-10T19:26:25Z"
6e123012d868c56aba8acabfe1ccad1bf8f20b04
7af13b6e3867198cd59c566a905b332888ea1dec
Move semantic classification caching down to Editor layer.
./src/Workspaces/Core/Portable/DesignerAttribute/DesignerAttributeHelpers.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.DesignerAttribute { internal static class DesignerAttributeHelpers { public static async Task<string?> ComputeDesignerAttributeCategoryAsync( INamedTypeSymbol? designerCategoryType, Document document, CancellationToken cancellationToken) { // simple case. If there's no DesignerCategory type in this compilation, then there's // definitely no designable types. Just immediately bail out. if (designerCategoryType == null) return null; var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); // Legacy behavior. We only register the designer info for the first non-nested class // in the file. var firstClass = FindFirstNonNestedClass( syntaxFacts, syntaxFacts.GetMembersOfCompilationUnit(root), cancellationToken); if (firstClass == null) return null; var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var firstClassType = (INamedTypeSymbol)semanticModel.GetRequiredDeclaredSymbol(firstClass, cancellationToken); return TryGetDesignerCategory(firstClassType, designerCategoryType, cancellationToken); } private static string? TryGetDesignerCategory( INamedTypeSymbol classType, INamedTypeSymbol designerCategoryType, CancellationToken cancellationToken) { foreach (var type in classType.GetBaseTypesAndThis()) { cancellationToken.ThrowIfCancellationRequested(); // if it has designer attribute, set it var attribute = type.GetAttributes().FirstOrDefault(d => designerCategoryType.Equals(d.AttributeClass)); if (attribute?.ConstructorArguments.Length == 1) return GetArgumentString(attribute.ConstructorArguments[0]); } return null; } private static SyntaxNode? FindFirstNonNestedClass( ISyntaxFactsService syntaxFacts, SyntaxList<SyntaxNode> members, CancellationToken cancellationToken) { foreach (var member in members) { cancellationToken.ThrowIfCancellationRequested(); if (syntaxFacts.IsNamespaceDeclaration(member)) { var firstClass = FindFirstNonNestedClass( syntaxFacts, syntaxFacts.GetMembersOfNamespaceDeclaration(member), cancellationToken); if (firstClass != null) return firstClass; } else if (syntaxFacts.IsClassDeclaration(member)) { return member; } } return null; } private static string? GetArgumentString(TypedConstant argument) { if (argument.Type == null || argument.Type.SpecialType != SpecialType.System_String || argument.IsNull || argument.Value is not string stringValue) { return null; } return stringValue.Trim(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.DesignerAttribute { internal static class DesignerAttributeHelpers { public static async Task<string?> ComputeDesignerAttributeCategoryAsync( INamedTypeSymbol? designerCategoryType, Document document, CancellationToken cancellationToken) { // simple case. If there's no DesignerCategory type in this compilation, then there's // definitely no designable types. Just immediately bail out. if (designerCategoryType == null) return null; var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); // Legacy behavior. We only register the designer info for the first non-nested class // in the file. var firstClass = FindFirstNonNestedClass( syntaxFacts, syntaxFacts.GetMembersOfCompilationUnit(root), cancellationToken); if (firstClass == null) return null; var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var firstClassType = (INamedTypeSymbol)semanticModel.GetRequiredDeclaredSymbol(firstClass, cancellationToken); return TryGetDesignerCategory(firstClassType, designerCategoryType, cancellationToken); } private static string? TryGetDesignerCategory( INamedTypeSymbol classType, INamedTypeSymbol designerCategoryType, CancellationToken cancellationToken) { foreach (var type in classType.GetBaseTypesAndThis()) { cancellationToken.ThrowIfCancellationRequested(); // if it has designer attribute, set it var attribute = type.GetAttributes().FirstOrDefault(d => designerCategoryType.Equals(d.AttributeClass)); if (attribute?.ConstructorArguments.Length == 1) return GetArgumentString(attribute.ConstructorArguments[0]); } return null; } private static SyntaxNode? FindFirstNonNestedClass( ISyntaxFactsService syntaxFacts, SyntaxList<SyntaxNode> members, CancellationToken cancellationToken) { foreach (var member in members) { cancellationToken.ThrowIfCancellationRequested(); if (syntaxFacts.IsNamespaceDeclaration(member)) { var firstClass = FindFirstNonNestedClass( syntaxFacts, syntaxFacts.GetMembersOfNamespaceDeclaration(member), cancellationToken); if (firstClass != null) return firstClass; } else if (syntaxFacts.IsClassDeclaration(member)) { return member; } } return null; } private static string? GetArgumentString(TypedConstant argument) { if (argument.Type == null || argument.Type.SpecialType != SpecialType.System_String || argument.IsNull || argument.Value is not string stringValue) { return null; } return stringValue.Trim(); } } }
-1
dotnet/roslyn
56,310
Move semantic classification caching down to Editor layer
CyrusNajmabadi
"2021-09-09T23:15:16Z"
"2021-09-10T19:26:25Z"
6e123012d868c56aba8acabfe1ccad1bf8f20b04
7af13b6e3867198cd59c566a905b332888ea1dec
Move semantic classification caching down to Editor layer.
./src/Compilers/CSharp/Portable/Symbols/Source/SourceOrdinaryMethodSymbolBase.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Globalization; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Unlike <see cref="SourceOrdinaryMethodSymbol"/>, this type doesn't depend /// on any specific kind of syntax node associated with it. Any syntax node is good enough /// for it. /// </summary> internal abstract class SourceOrdinaryMethodSymbolBase : SourceOrdinaryMethodOrUserDefinedOperatorSymbol { private readonly ImmutableArray<TypeParameterSymbol> _typeParameters; private readonly string _name; protected SourceOrdinaryMethodSymbolBase( NamedTypeSymbol containingType, string name, Location location, CSharpSyntaxNode syntax, MethodKind methodKind, bool isIterator, bool isExtensionMethod, bool isPartial, bool isReadOnly, bool hasBody, bool isNullableAnalysisEnabled, BindingDiagnosticBag diagnostics) : base(containingType, syntax.GetReference(), location, isIterator: isIterator) { Debug.Assert(diagnostics.DiagnosticBag is object); Debug.Assert(!isReadOnly || this.IsImplicitlyDeclared, "We only expect synthesized methods to use this flag to make a method readonly. Explicitly declared methods should get this value from modifiers in syntax."); _name = name; // The following two values are used to compute and store the initial value of the flags // However, these two components are placeholders; the correct value will be // computed lazily later and then the flags will be fixed up. const bool returnsVoid = false; DeclarationModifiers declarationModifiers; (declarationModifiers, HasExplicitAccessModifier) = this.MakeModifiers(methodKind, isPartial, isReadOnly, hasBody, location, diagnostics); //explicit impls must be marked metadata virtual unless static var isMetadataVirtualIgnoringModifiers = methodKind == MethodKind.ExplicitInterfaceImplementation && (declarationModifiers & DeclarationModifiers.Static) == 0; this.MakeFlags(methodKind, declarationModifiers, returnsVoid, isExtensionMethod: isExtensionMethod, isNullableAnalysisEnabled: isNullableAnalysisEnabled, isMetadataVirtualIgnoringModifiers: isMetadataVirtualIgnoringModifiers); _typeParameters = MakeTypeParameters(syntax, diagnostics); CheckFeatureAvailabilityAndRuntimeSupport(syntax, location, hasBody, diagnostics); if (hasBody) { CheckModifiersForBody(location, diagnostics); } var info = ModifierUtils.CheckAccessibility(this.DeclarationModifiers, this, isExplicitInterfaceImplementation: methodKind == MethodKind.ExplicitInterfaceImplementation); if (info != null) { diagnostics.Add(info, location); } } protected abstract ImmutableArray<TypeParameterSymbol> MakeTypeParameters(CSharpSyntaxNode node, BindingDiagnosticBag diagnostics); #nullable enable protected override void MethodChecks(BindingDiagnosticBag diagnostics) { Debug.Assert(this.MethodKind != MethodKind.UserDefinedOperator, "SourceUserDefinedOperatorSymbolBase overrides this"); var (returnType, parameters, isVararg, declaredConstraints) = MakeParametersAndBindReturnType(diagnostics); MethodSymbol? overriddenOrExplicitlyImplementedMethod = MethodChecks(returnType, parameters, diagnostics); if (!declaredConstraints.IsDefault && overriddenOrExplicitlyImplementedMethod is object) { for (int i = 0; i < declaredConstraints.Length; i++) { var typeParameter = _typeParameters[i]; ErrorCode report; switch (declaredConstraints[i].Constraints & (TypeParameterConstraintKind.ReferenceType | TypeParameterConstraintKind.ValueType | TypeParameterConstraintKind.Default)) { case TypeParameterConstraintKind.ReferenceType: if (!typeParameter.IsReferenceType) { report = ErrorCode.ERR_OverrideRefConstraintNotSatisfied; break; } continue; case TypeParameterConstraintKind.ValueType: if (!typeParameter.IsNonNullableValueType()) { report = ErrorCode.ERR_OverrideValConstraintNotSatisfied; break; } continue; case TypeParameterConstraintKind.Default: if (typeParameter.IsReferenceType || typeParameter.IsValueType) { report = ErrorCode.ERR_OverrideDefaultConstraintNotSatisfied; break; } continue; default: continue; } diagnostics.Add(report, typeParameter.Locations[0], this, typeParameter, overriddenOrExplicitlyImplementedMethod.TypeParameters[i], overriddenOrExplicitlyImplementedMethod); } } CheckModifiers(MethodKind == MethodKind.ExplicitInterfaceImplementation, isVararg, HasAnyBody, locations[0], diagnostics); } #nullable disable protected abstract (TypeWithAnnotations ReturnType, ImmutableArray<ParameterSymbol> Parameters, bool IsVararg, ImmutableArray<TypeParameterConstraintClause> DeclaredConstraintsForOverrideOrImplementation) MakeParametersAndBindReturnType(BindingDiagnosticBag diagnostics); protected abstract bool HasAnyBody { get; } protected sealed override void LazyAsyncMethodChecks(CancellationToken cancellationToken) { Debug.Assert(this.IsPartial == state.HasComplete(CompletionPart.FinishMethodChecks), "Partial methods complete method checks during construction. " + "Other methods can't complete method checks before executing this method."); if (!this.IsAsync) { CompleteAsyncMethodChecks(diagnosticsOpt: null, cancellationToken: cancellationToken); return; } var diagnostics = BindingDiagnosticBag.GetInstance(); AsyncMethodChecks(diagnostics); CompleteAsyncMethodChecks(diagnostics, cancellationToken); diagnostics.Free(); } private void CompleteAsyncMethodChecks(BindingDiagnosticBag diagnosticsOpt, CancellationToken cancellationToken) { if (state.NotePartComplete(CompletionPart.StartAsyncMethodChecks)) { if (diagnosticsOpt != null) { AddDeclarationDiagnostics(diagnosticsOpt); } CompleteAsyncMethodChecksBetweenStartAndFinish(); state.NotePartComplete(CompletionPart.FinishAsyncMethodChecks); } else { state.SpinWaitComplete(CompletionPart.FinishAsyncMethodChecks, cancellationToken); } } protected abstract void CompleteAsyncMethodChecksBetweenStartAndFinish(); public override ImmutableArray<TypeParameterSymbol> TypeParameters { get { return _typeParameters; } } public override ImmutableArray<Location> Locations { get { return this.locations; } } public abstract override string GetDocumentationCommentXml(CultureInfo preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default(CancellationToken)); public override string Name { get { return _name; } } protected abstract override SourceMemberMethodSymbol BoundAttributesSource { get; } internal abstract override OneOrMany<SyntaxList<AttributeListSyntax>> GetAttributeDeclarations(); internal bool HasExplicitAccessModifier { get; } private (DeclarationModifiers mods, bool hasExplicitAccessMod) MakeModifiers(MethodKind methodKind, bool isPartial, bool isReadOnly, bool hasBody, Location location, BindingDiagnosticBag diagnostics) { bool isInterface = this.ContainingType.IsInterface; bool isExplicitInterfaceImplementation = methodKind == MethodKind.ExplicitInterfaceImplementation; var defaultAccess = isInterface && isPartial && !isExplicitInterfaceImplementation ? DeclarationModifiers.Public : DeclarationModifiers.Private; // Check that the set of modifiers is allowed var allowedModifiers = DeclarationModifiers.Partial | DeclarationModifiers.Unsafe; var defaultInterfaceImplementationModifiers = DeclarationModifiers.None; if (!isExplicitInterfaceImplementation) { allowedModifiers |= DeclarationModifiers.New | DeclarationModifiers.Sealed | DeclarationModifiers.Abstract | DeclarationModifiers.Static | DeclarationModifiers.Virtual | DeclarationModifiers.AccessibilityMask; if (!isInterface) { allowedModifiers |= DeclarationModifiers.Override; } else { // This is needed to make sure we can detect 'public' modifier specified explicitly and // check it against language version below. defaultAccess = DeclarationModifiers.None; defaultInterfaceImplementationModifiers |= DeclarationModifiers.Sealed | DeclarationModifiers.Abstract | DeclarationModifiers.Static | DeclarationModifiers.Virtual | DeclarationModifiers.Extern | DeclarationModifiers.Async | DeclarationModifiers.Partial | DeclarationModifiers.AccessibilityMask; } } else { Debug.Assert(isExplicitInterfaceImplementation); if (isInterface) { allowedModifiers |= DeclarationModifiers.Abstract; } else { allowedModifiers |= DeclarationModifiers.Static; } } allowedModifiers |= DeclarationModifiers.Extern | DeclarationModifiers.Async; if (ContainingType.IsStructType()) { allowedModifiers |= DeclarationModifiers.ReadOnly; } // In order to detect whether explicit accessibility mods were provided, we pass the default value // for 'defaultAccess' and manually add in the 'defaultAccess' flags after the call. bool hasExplicitAccessMod; DeclarationModifiers mods = MakeDeclarationModifiers(allowedModifiers, diagnostics); if ((mods & DeclarationModifiers.AccessibilityMask) == 0) { hasExplicitAccessMod = false; mods |= defaultAccess; } else { hasExplicitAccessMod = true; } if (isReadOnly) { Debug.Assert(ContainingType.IsStructType()); mods |= DeclarationModifiers.ReadOnly; } ModifierUtils.CheckFeatureAvailabilityForStaticAbstractMembersInInterfacesIfNeeded(mods, isExplicitInterfaceImplementation, location, diagnostics); this.CheckUnsafeModifier(mods, diagnostics); ModifierUtils.ReportDefaultInterfaceImplementationModifiers(hasBody, mods, defaultInterfaceImplementationModifiers, location, diagnostics); mods = AddImpliedModifiers(mods, isInterface, methodKind, hasBody); return (mods, hasExplicitAccessMod); } protected abstract DeclarationModifiers MakeDeclarationModifiers(DeclarationModifiers allowedModifiers, BindingDiagnosticBag diagnostics); private static DeclarationModifiers AddImpliedModifiers(DeclarationModifiers mods, bool containingTypeIsInterface, MethodKind methodKind, bool hasBody) { // Let's overwrite modifiers for interface and explicit interface implementation methods with what they are supposed to be. // Proper errors must have been reported by now. if (containingTypeIsInterface) { mods = ModifierUtils.AdjustModifiersForAnInterfaceMember(mods, hasBody, methodKind == MethodKind.ExplicitInterfaceImplementation); } else if (methodKind == MethodKind.ExplicitInterfaceImplementation) { mods = (mods & ~DeclarationModifiers.AccessibilityMask) | DeclarationModifiers.Private; } return mods; } private const DeclarationModifiers PartialMethodExtendedModifierMask = DeclarationModifiers.Virtual | DeclarationModifiers.Override | DeclarationModifiers.New | DeclarationModifiers.Sealed | DeclarationModifiers.Extern; internal bool HasExtendedPartialModifier => (DeclarationModifiers & PartialMethodExtendedModifierMask) != 0; private void CheckModifiers(bool isExplicitInterfaceImplementation, bool isVararg, bool hasBody, Location location, BindingDiagnosticBag diagnostics) { Debug.Assert(!IsStatic || (!IsVirtual && !IsOverride)); // Otherwise 'virtual' and 'override' should have been reported and cleared earlier. bool isExplicitInterfaceImplementationInInterface = isExplicitInterfaceImplementation && ContainingType.IsInterface; if (IsPartial && HasExplicitAccessModifier) { Binder.CheckFeatureAvailability(SyntaxNode, MessageID.IDS_FeatureExtendedPartialMethods, diagnostics, location); } if (IsPartial && IsAbstract) { diagnostics.Add(ErrorCode.ERR_PartialMethodInvalidModifier, location); } else if (IsPartial && !HasExplicitAccessModifier && !ReturnsVoid) { diagnostics.Add(ErrorCode.ERR_PartialMethodWithNonVoidReturnMustHaveAccessMods, location, this); } else if (IsPartial && !HasExplicitAccessModifier && HasExtendedPartialModifier) { diagnostics.Add(ErrorCode.ERR_PartialMethodWithExtendedModMustHaveAccessMods, location, this); } else if (IsPartial && !HasExplicitAccessModifier && Parameters.Any(p => p.RefKind == RefKind.Out)) { diagnostics.Add(ErrorCode.ERR_PartialMethodWithOutParamMustHaveAccessMods, location, this); } else if (this.DeclaredAccessibility == Accessibility.Private && (IsVirtual || (IsAbstract && !isExplicitInterfaceImplementationInInterface) || IsOverride)) { diagnostics.Add(ErrorCode.ERR_VirtualPrivate, location, this); } else if (IsStatic && IsAbstract && !ContainingType.IsInterface) { // A static member '{0}' cannot be marked as 'abstract' diagnostics.Add(ErrorCode.ERR_StaticNotVirtual, location, ModifierUtils.ConvertSingleModifierToSyntaxText(DeclarationModifiers.Abstract)); } else if (IsOverride && (IsNew || IsVirtual)) { // A member '{0}' marked as override cannot be marked as new or virtual diagnostics.Add(ErrorCode.ERR_OverrideNotNew, location, this); } else if (IsSealed && !IsOverride && !(isExplicitInterfaceImplementationInInterface && IsAbstract)) { // '{0}' cannot be sealed because it is not an override diagnostics.Add(ErrorCode.ERR_SealedNonOverride, location, this); } else if (IsSealed && ContainingType.TypeKind == TypeKind.Struct) { // The modifier '{0}' is not valid for this item diagnostics.Add(ErrorCode.ERR_BadMemberFlag, location, SyntaxFacts.GetText(SyntaxKind.SealedKeyword)); } else if (ReturnType.IsStatic) { // '{0}': static types cannot be used as return types diagnostics.Add(ErrorFacts.GetStaticClassReturnCode(ContainingType.IsInterfaceType()), location, ReturnType); } else if (IsAbstract && IsExtern) { diagnostics.Add(ErrorCode.ERR_AbstractAndExtern, location, this); } else if (IsAbstract && IsSealed && !isExplicitInterfaceImplementationInInterface) { diagnostics.Add(ErrorCode.ERR_AbstractAndSealed, location, this); } else if (IsAbstract && IsVirtual) { diagnostics.Add(ErrorCode.ERR_AbstractNotVirtual, location, this.Kind.Localize(), this); } else if (IsAbstract && ContainingType.TypeKind == TypeKind.Struct) { // The modifier '{0}' is not valid for this item diagnostics.Add(ErrorCode.ERR_BadMemberFlag, location, SyntaxFacts.GetText(SyntaxKind.AbstractKeyword)); } else if (IsVirtual && ContainingType.TypeKind == TypeKind.Struct) { // The modifier '{0}' is not valid for this item diagnostics.Add(ErrorCode.ERR_BadMemberFlag, location, SyntaxFacts.GetText(SyntaxKind.VirtualKeyword)); } else if (IsStatic && IsDeclaredReadOnly) { // Static member '{0}' cannot be marked 'readonly'. diagnostics.Add(ErrorCode.ERR_StaticMemberCantBeReadOnly, location, this); } else if (IsAbstract && !ContainingType.IsAbstract && (ContainingType.TypeKind == TypeKind.Class || ContainingType.TypeKind == TypeKind.Submission)) { // '{0}' is abstract but it is contained in non-abstract type '{1}' diagnostics.Add(ErrorCode.ERR_AbstractInConcreteClass, location, this, ContainingType); } else if (IsVirtual && ContainingType.IsSealed) { // '{0}' is a new virtual member in sealed type '{1}' diagnostics.Add(ErrorCode.ERR_NewVirtualInSealed, location, this, ContainingType); } else if (!hasBody && IsAsync) { diagnostics.Add(ErrorCode.ERR_BadAsyncLacksBody, location); } else if (!hasBody && !IsExtern && !IsAbstract && !IsPartial && !IsExpressionBodied) { diagnostics.Add(ErrorCode.ERR_ConcreteMissingBody, location, this); } else if (ContainingType.IsSealed && this.DeclaredAccessibility.HasProtected() && !this.IsOverride) { diagnostics.Add(AccessCheck.GetProtectedMemberInSealedTypeError(ContainingType), location, this); } else if (ContainingType.IsStatic && !IsStatic) { diagnostics.Add(ErrorCode.ERR_InstanceMemberInStaticClass, location, Name); } else if (isVararg && (IsGenericMethod || ContainingType.IsGenericType || Parameters.Length > 0 && Parameters[Parameters.Length - 1].IsParams)) { diagnostics.Add(ErrorCode.ERR_BadVarargs, location); } else if (isVararg && IsAsync) { diagnostics.Add(ErrorCode.ERR_VarargsAsync, location); } } internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedAttributes(moduleBuilder, ref attributes); if (this.IsExtensionMethod) { // No need to check if [Extension] attribute was explicitly set since // we'll issue CS1112 error in those cases and won't generate IL. var compilation = this.DeclaringCompilation; AddSynthesizedAttribute(ref attributes, compilation.TrySynthesizeAttribute( WellKnownMember.System_Runtime_CompilerServices_ExtensionAttribute__ctor)); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Globalization; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Unlike <see cref="SourceOrdinaryMethodSymbol"/>, this type doesn't depend /// on any specific kind of syntax node associated with it. Any syntax node is good enough /// for it. /// </summary> internal abstract class SourceOrdinaryMethodSymbolBase : SourceOrdinaryMethodOrUserDefinedOperatorSymbol { private readonly ImmutableArray<TypeParameterSymbol> _typeParameters; private readonly string _name; protected SourceOrdinaryMethodSymbolBase( NamedTypeSymbol containingType, string name, Location location, CSharpSyntaxNode syntax, MethodKind methodKind, bool isIterator, bool isExtensionMethod, bool isPartial, bool isReadOnly, bool hasBody, bool isNullableAnalysisEnabled, BindingDiagnosticBag diagnostics) : base(containingType, syntax.GetReference(), location, isIterator: isIterator) { Debug.Assert(diagnostics.DiagnosticBag is object); Debug.Assert(!isReadOnly || this.IsImplicitlyDeclared, "We only expect synthesized methods to use this flag to make a method readonly. Explicitly declared methods should get this value from modifiers in syntax."); _name = name; // The following two values are used to compute and store the initial value of the flags // However, these two components are placeholders; the correct value will be // computed lazily later and then the flags will be fixed up. const bool returnsVoid = false; DeclarationModifiers declarationModifiers; (declarationModifiers, HasExplicitAccessModifier) = this.MakeModifiers(methodKind, isPartial, isReadOnly, hasBody, location, diagnostics); //explicit impls must be marked metadata virtual unless static var isMetadataVirtualIgnoringModifiers = methodKind == MethodKind.ExplicitInterfaceImplementation && (declarationModifiers & DeclarationModifiers.Static) == 0; this.MakeFlags(methodKind, declarationModifiers, returnsVoid, isExtensionMethod: isExtensionMethod, isNullableAnalysisEnabled: isNullableAnalysisEnabled, isMetadataVirtualIgnoringModifiers: isMetadataVirtualIgnoringModifiers); _typeParameters = MakeTypeParameters(syntax, diagnostics); CheckFeatureAvailabilityAndRuntimeSupport(syntax, location, hasBody, diagnostics); if (hasBody) { CheckModifiersForBody(location, diagnostics); } var info = ModifierUtils.CheckAccessibility(this.DeclarationModifiers, this, isExplicitInterfaceImplementation: methodKind == MethodKind.ExplicitInterfaceImplementation); if (info != null) { diagnostics.Add(info, location); } } protected abstract ImmutableArray<TypeParameterSymbol> MakeTypeParameters(CSharpSyntaxNode node, BindingDiagnosticBag diagnostics); #nullable enable protected override void MethodChecks(BindingDiagnosticBag diagnostics) { Debug.Assert(this.MethodKind != MethodKind.UserDefinedOperator, "SourceUserDefinedOperatorSymbolBase overrides this"); var (returnType, parameters, isVararg, declaredConstraints) = MakeParametersAndBindReturnType(diagnostics); MethodSymbol? overriddenOrExplicitlyImplementedMethod = MethodChecks(returnType, parameters, diagnostics); if (!declaredConstraints.IsDefault && overriddenOrExplicitlyImplementedMethod is object) { for (int i = 0; i < declaredConstraints.Length; i++) { var typeParameter = _typeParameters[i]; ErrorCode report; switch (declaredConstraints[i].Constraints & (TypeParameterConstraintKind.ReferenceType | TypeParameterConstraintKind.ValueType | TypeParameterConstraintKind.Default)) { case TypeParameterConstraintKind.ReferenceType: if (!typeParameter.IsReferenceType) { report = ErrorCode.ERR_OverrideRefConstraintNotSatisfied; break; } continue; case TypeParameterConstraintKind.ValueType: if (!typeParameter.IsNonNullableValueType()) { report = ErrorCode.ERR_OverrideValConstraintNotSatisfied; break; } continue; case TypeParameterConstraintKind.Default: if (typeParameter.IsReferenceType || typeParameter.IsValueType) { report = ErrorCode.ERR_OverrideDefaultConstraintNotSatisfied; break; } continue; default: continue; } diagnostics.Add(report, typeParameter.Locations[0], this, typeParameter, overriddenOrExplicitlyImplementedMethod.TypeParameters[i], overriddenOrExplicitlyImplementedMethod); } } CheckModifiers(MethodKind == MethodKind.ExplicitInterfaceImplementation, isVararg, HasAnyBody, locations[0], diagnostics); } #nullable disable protected abstract (TypeWithAnnotations ReturnType, ImmutableArray<ParameterSymbol> Parameters, bool IsVararg, ImmutableArray<TypeParameterConstraintClause> DeclaredConstraintsForOverrideOrImplementation) MakeParametersAndBindReturnType(BindingDiagnosticBag diagnostics); protected abstract bool HasAnyBody { get; } protected sealed override void LazyAsyncMethodChecks(CancellationToken cancellationToken) { Debug.Assert(this.IsPartial == state.HasComplete(CompletionPart.FinishMethodChecks), "Partial methods complete method checks during construction. " + "Other methods can't complete method checks before executing this method."); if (!this.IsAsync) { CompleteAsyncMethodChecks(diagnosticsOpt: null, cancellationToken: cancellationToken); return; } var diagnostics = BindingDiagnosticBag.GetInstance(); AsyncMethodChecks(diagnostics); CompleteAsyncMethodChecks(diagnostics, cancellationToken); diagnostics.Free(); } private void CompleteAsyncMethodChecks(BindingDiagnosticBag diagnosticsOpt, CancellationToken cancellationToken) { if (state.NotePartComplete(CompletionPart.StartAsyncMethodChecks)) { if (diagnosticsOpt != null) { AddDeclarationDiagnostics(diagnosticsOpt); } CompleteAsyncMethodChecksBetweenStartAndFinish(); state.NotePartComplete(CompletionPart.FinishAsyncMethodChecks); } else { state.SpinWaitComplete(CompletionPart.FinishAsyncMethodChecks, cancellationToken); } } protected abstract void CompleteAsyncMethodChecksBetweenStartAndFinish(); public override ImmutableArray<TypeParameterSymbol> TypeParameters { get { return _typeParameters; } } public override ImmutableArray<Location> Locations { get { return this.locations; } } public abstract override string GetDocumentationCommentXml(CultureInfo preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default(CancellationToken)); public override string Name { get { return _name; } } protected abstract override SourceMemberMethodSymbol BoundAttributesSource { get; } internal abstract override OneOrMany<SyntaxList<AttributeListSyntax>> GetAttributeDeclarations(); internal bool HasExplicitAccessModifier { get; } private (DeclarationModifiers mods, bool hasExplicitAccessMod) MakeModifiers(MethodKind methodKind, bool isPartial, bool isReadOnly, bool hasBody, Location location, BindingDiagnosticBag diagnostics) { bool isInterface = this.ContainingType.IsInterface; bool isExplicitInterfaceImplementation = methodKind == MethodKind.ExplicitInterfaceImplementation; var defaultAccess = isInterface && isPartial && !isExplicitInterfaceImplementation ? DeclarationModifiers.Public : DeclarationModifiers.Private; // Check that the set of modifiers is allowed var allowedModifiers = DeclarationModifiers.Partial | DeclarationModifiers.Unsafe; var defaultInterfaceImplementationModifiers = DeclarationModifiers.None; if (!isExplicitInterfaceImplementation) { allowedModifiers |= DeclarationModifiers.New | DeclarationModifiers.Sealed | DeclarationModifiers.Abstract | DeclarationModifiers.Static | DeclarationModifiers.Virtual | DeclarationModifiers.AccessibilityMask; if (!isInterface) { allowedModifiers |= DeclarationModifiers.Override; } else { // This is needed to make sure we can detect 'public' modifier specified explicitly and // check it against language version below. defaultAccess = DeclarationModifiers.None; defaultInterfaceImplementationModifiers |= DeclarationModifiers.Sealed | DeclarationModifiers.Abstract | DeclarationModifiers.Static | DeclarationModifiers.Virtual | DeclarationModifiers.Extern | DeclarationModifiers.Async | DeclarationModifiers.Partial | DeclarationModifiers.AccessibilityMask; } } else { Debug.Assert(isExplicitInterfaceImplementation); if (isInterface) { allowedModifiers |= DeclarationModifiers.Abstract; } else { allowedModifiers |= DeclarationModifiers.Static; } } allowedModifiers |= DeclarationModifiers.Extern | DeclarationModifiers.Async; if (ContainingType.IsStructType()) { allowedModifiers |= DeclarationModifiers.ReadOnly; } // In order to detect whether explicit accessibility mods were provided, we pass the default value // for 'defaultAccess' and manually add in the 'defaultAccess' flags after the call. bool hasExplicitAccessMod; DeclarationModifiers mods = MakeDeclarationModifiers(allowedModifiers, diagnostics); if ((mods & DeclarationModifiers.AccessibilityMask) == 0) { hasExplicitAccessMod = false; mods |= defaultAccess; } else { hasExplicitAccessMod = true; } if (isReadOnly) { Debug.Assert(ContainingType.IsStructType()); mods |= DeclarationModifiers.ReadOnly; } ModifierUtils.CheckFeatureAvailabilityForStaticAbstractMembersInInterfacesIfNeeded(mods, isExplicitInterfaceImplementation, location, diagnostics); this.CheckUnsafeModifier(mods, diagnostics); ModifierUtils.ReportDefaultInterfaceImplementationModifiers(hasBody, mods, defaultInterfaceImplementationModifiers, location, diagnostics); mods = AddImpliedModifiers(mods, isInterface, methodKind, hasBody); return (mods, hasExplicitAccessMod); } protected abstract DeclarationModifiers MakeDeclarationModifiers(DeclarationModifiers allowedModifiers, BindingDiagnosticBag diagnostics); private static DeclarationModifiers AddImpliedModifiers(DeclarationModifiers mods, bool containingTypeIsInterface, MethodKind methodKind, bool hasBody) { // Let's overwrite modifiers for interface and explicit interface implementation methods with what they are supposed to be. // Proper errors must have been reported by now. if (containingTypeIsInterface) { mods = ModifierUtils.AdjustModifiersForAnInterfaceMember(mods, hasBody, methodKind == MethodKind.ExplicitInterfaceImplementation); } else if (methodKind == MethodKind.ExplicitInterfaceImplementation) { mods = (mods & ~DeclarationModifiers.AccessibilityMask) | DeclarationModifiers.Private; } return mods; } private const DeclarationModifiers PartialMethodExtendedModifierMask = DeclarationModifiers.Virtual | DeclarationModifiers.Override | DeclarationModifiers.New | DeclarationModifiers.Sealed | DeclarationModifiers.Extern; internal bool HasExtendedPartialModifier => (DeclarationModifiers & PartialMethodExtendedModifierMask) != 0; private void CheckModifiers(bool isExplicitInterfaceImplementation, bool isVararg, bool hasBody, Location location, BindingDiagnosticBag diagnostics) { Debug.Assert(!IsStatic || (!IsVirtual && !IsOverride)); // Otherwise 'virtual' and 'override' should have been reported and cleared earlier. bool isExplicitInterfaceImplementationInInterface = isExplicitInterfaceImplementation && ContainingType.IsInterface; if (IsPartial && HasExplicitAccessModifier) { Binder.CheckFeatureAvailability(SyntaxNode, MessageID.IDS_FeatureExtendedPartialMethods, diagnostics, location); } if (IsPartial && IsAbstract) { diagnostics.Add(ErrorCode.ERR_PartialMethodInvalidModifier, location); } else if (IsPartial && !HasExplicitAccessModifier && !ReturnsVoid) { diagnostics.Add(ErrorCode.ERR_PartialMethodWithNonVoidReturnMustHaveAccessMods, location, this); } else if (IsPartial && !HasExplicitAccessModifier && HasExtendedPartialModifier) { diagnostics.Add(ErrorCode.ERR_PartialMethodWithExtendedModMustHaveAccessMods, location, this); } else if (IsPartial && !HasExplicitAccessModifier && Parameters.Any(p => p.RefKind == RefKind.Out)) { diagnostics.Add(ErrorCode.ERR_PartialMethodWithOutParamMustHaveAccessMods, location, this); } else if (this.DeclaredAccessibility == Accessibility.Private && (IsVirtual || (IsAbstract && !isExplicitInterfaceImplementationInInterface) || IsOverride)) { diagnostics.Add(ErrorCode.ERR_VirtualPrivate, location, this); } else if (IsStatic && IsAbstract && !ContainingType.IsInterface) { // A static member '{0}' cannot be marked as 'abstract' diagnostics.Add(ErrorCode.ERR_StaticNotVirtual, location, ModifierUtils.ConvertSingleModifierToSyntaxText(DeclarationModifiers.Abstract)); } else if (IsOverride && (IsNew || IsVirtual)) { // A member '{0}' marked as override cannot be marked as new or virtual diagnostics.Add(ErrorCode.ERR_OverrideNotNew, location, this); } else if (IsSealed && !IsOverride && !(isExplicitInterfaceImplementationInInterface && IsAbstract)) { // '{0}' cannot be sealed because it is not an override diagnostics.Add(ErrorCode.ERR_SealedNonOverride, location, this); } else if (IsSealed && ContainingType.TypeKind == TypeKind.Struct) { // The modifier '{0}' is not valid for this item diagnostics.Add(ErrorCode.ERR_BadMemberFlag, location, SyntaxFacts.GetText(SyntaxKind.SealedKeyword)); } else if (ReturnType.IsStatic) { // '{0}': static types cannot be used as return types diagnostics.Add(ErrorFacts.GetStaticClassReturnCode(ContainingType.IsInterfaceType()), location, ReturnType); } else if (IsAbstract && IsExtern) { diagnostics.Add(ErrorCode.ERR_AbstractAndExtern, location, this); } else if (IsAbstract && IsSealed && !isExplicitInterfaceImplementationInInterface) { diagnostics.Add(ErrorCode.ERR_AbstractAndSealed, location, this); } else if (IsAbstract && IsVirtual) { diagnostics.Add(ErrorCode.ERR_AbstractNotVirtual, location, this.Kind.Localize(), this); } else if (IsAbstract && ContainingType.TypeKind == TypeKind.Struct) { // The modifier '{0}' is not valid for this item diagnostics.Add(ErrorCode.ERR_BadMemberFlag, location, SyntaxFacts.GetText(SyntaxKind.AbstractKeyword)); } else if (IsVirtual && ContainingType.TypeKind == TypeKind.Struct) { // The modifier '{0}' is not valid for this item diagnostics.Add(ErrorCode.ERR_BadMemberFlag, location, SyntaxFacts.GetText(SyntaxKind.VirtualKeyword)); } else if (IsStatic && IsDeclaredReadOnly) { // Static member '{0}' cannot be marked 'readonly'. diagnostics.Add(ErrorCode.ERR_StaticMemberCantBeReadOnly, location, this); } else if (IsAbstract && !ContainingType.IsAbstract && (ContainingType.TypeKind == TypeKind.Class || ContainingType.TypeKind == TypeKind.Submission)) { // '{0}' is abstract but it is contained in non-abstract type '{1}' diagnostics.Add(ErrorCode.ERR_AbstractInConcreteClass, location, this, ContainingType); } else if (IsVirtual && ContainingType.IsSealed) { // '{0}' is a new virtual member in sealed type '{1}' diagnostics.Add(ErrorCode.ERR_NewVirtualInSealed, location, this, ContainingType); } else if (!hasBody && IsAsync) { diagnostics.Add(ErrorCode.ERR_BadAsyncLacksBody, location); } else if (!hasBody && !IsExtern && !IsAbstract && !IsPartial && !IsExpressionBodied) { diagnostics.Add(ErrorCode.ERR_ConcreteMissingBody, location, this); } else if (ContainingType.IsSealed && this.DeclaredAccessibility.HasProtected() && !this.IsOverride) { diagnostics.Add(AccessCheck.GetProtectedMemberInSealedTypeError(ContainingType), location, this); } else if (ContainingType.IsStatic && !IsStatic) { diagnostics.Add(ErrorCode.ERR_InstanceMemberInStaticClass, location, Name); } else if (isVararg && (IsGenericMethod || ContainingType.IsGenericType || Parameters.Length > 0 && Parameters[Parameters.Length - 1].IsParams)) { diagnostics.Add(ErrorCode.ERR_BadVarargs, location); } else if (isVararg && IsAsync) { diagnostics.Add(ErrorCode.ERR_VarargsAsync, location); } } internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedAttributes(moduleBuilder, ref attributes); if (this.IsExtensionMethod) { // No need to check if [Extension] attribute was explicitly set since // we'll issue CS1112 error in those cases and won't generate IL. var compilation = this.DeclaringCompilation; AddSynthesizedAttribute(ref attributes, compilation.TrySynthesizeAttribute( WellKnownMember.System_Runtime_CompilerServices_ExtensionAttribute__ctor)); } } } }
-1
dotnet/roslyn
56,310
Move semantic classification caching down to Editor layer
CyrusNajmabadi
"2021-09-09T23:15:16Z"
"2021-09-10T19:26:25Z"
6e123012d868c56aba8acabfe1ccad1bf8f20b04
7af13b6e3867198cd59c566a905b332888ea1dec
Move semantic classification caching down to Editor layer.
./src/EditorFeatures/Core.Wpf/Interactive/InteractiveEvaluatorResetOptions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. extern alias InteractiveHost; using InteractiveHost::Microsoft.CodeAnalysis.Interactive; namespace Microsoft.CodeAnalysis.Editor.Interactive { internal sealed class InteractiveEvaluatorResetOptions { public readonly InteractiveHostPlatform? Platform; public InteractiveEvaluatorResetOptions(InteractiveHostPlatform? platform) => Platform = platform; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. extern alias InteractiveHost; using InteractiveHost::Microsoft.CodeAnalysis.Interactive; namespace Microsoft.CodeAnalysis.Editor.Interactive { internal sealed class InteractiveEvaluatorResetOptions { public readonly InteractiveHostPlatform? Platform; public InteractiveEvaluatorResetOptions(InteractiveHostPlatform? platform) => Platform = platform; } }
-1
dotnet/roslyn
56,310
Move semantic classification caching down to Editor layer
CyrusNajmabadi
"2021-09-09T23:15:16Z"
"2021-09-10T19:26:25Z"
6e123012d868c56aba8acabfe1ccad1bf8f20b04
7af13b6e3867198cd59c566a905b332888ea1dec
Move semantic classification caching down to Editor layer.
./src/Features/CSharp/Portable/LanguageServices/CSharpSymbolDisplayService.SymbolDescriptionBuilder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.CSharp.LanguageServices { internal partial class CSharpSymbolDisplayService { protected class SymbolDescriptionBuilder : AbstractSymbolDescriptionBuilder { private static readonly SymbolDisplayFormat s_minimallyQualifiedFormat = SymbolDisplayFormat.MinimallyQualifiedFormat .AddLocalOptions(SymbolDisplayLocalOptions.IncludeRef) .AddMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.UseErrorTypeSymbolName) .RemoveParameterOptions(SymbolDisplayParameterOptions.IncludeDefaultValue) .WithKindOptions(SymbolDisplayKindOptions.None); private static readonly SymbolDisplayFormat s_minimallyQualifiedFormatWithConstants = s_minimallyQualifiedFormat .AddLocalOptions(SymbolDisplayLocalOptions.IncludeConstantValue) .AddMemberOptions(SymbolDisplayMemberOptions.IncludeConstantValue) .AddParameterOptions(SymbolDisplayParameterOptions.IncludeDefaultValue); private static readonly SymbolDisplayFormat s_minimallyQualifiedFormatWithConstantsAndModifiers = s_minimallyQualifiedFormatWithConstants .AddMemberOptions(SymbolDisplayMemberOptions.IncludeModifiers); public SymbolDescriptionBuilder( SemanticModel semanticModel, int position, Workspace workspace, IAnonymousTypeDisplayService anonymousTypeDisplayService, CancellationToken cancellationToken) : base(semanticModel, position, workspace, anonymousTypeDisplayService, cancellationToken) { } protected override void AddDeprecatedPrefix() { AddToGroup(SymbolDescriptionGroups.MainDescription, Punctuation("["), PlainText(CSharpFeaturesResources.deprecated), Punctuation("]"), Space()); } protected override void AddExtensionPrefix() { AddToGroup(SymbolDescriptionGroups.MainDescription, Punctuation("("), PlainText(CSharpFeaturesResources.extension), Punctuation(")"), Space()); } protected override void AddAwaitablePrefix() { AddToGroup(SymbolDescriptionGroups.MainDescription, Punctuation("("), PlainText(CSharpFeaturesResources.awaitable), Punctuation(")"), Space()); } protected override void AddAwaitableExtensionPrefix() { AddToGroup(SymbolDescriptionGroups.MainDescription, Punctuation("("), PlainText(CSharpFeaturesResources.awaitable_extension), Punctuation(")"), Space()); } protected override void AddEnumUnderlyingTypeSeparator() { AddToGroup(SymbolDescriptionGroups.MainDescription, Space(), Punctuation(":"), Space()); } protected override Task<ImmutableArray<SymbolDisplayPart>> GetInitializerSourcePartsAsync( ISymbol symbol) { // Actually check for C# symbol types here. if (symbol is IParameterSymbol parameter) { return GetInitializerSourcePartsAsync(parameter); } else if (symbol is ILocalSymbol local) { return GetInitializerSourcePartsAsync(local); } else if (symbol is IFieldSymbol field) { return GetInitializerSourcePartsAsync(field); } return SpecializedTasks.EmptyImmutableArray<SymbolDisplayPart>(); } protected override ImmutableArray<SymbolDisplayPart> ToMinimalDisplayParts(ISymbol symbol, SemanticModel semanticModel, int position, SymbolDisplayFormat format) => CodeAnalysis.CSharp.SymbolDisplay.ToMinimalDisplayParts(symbol, semanticModel, position, format); protected override string GetNavigationHint(ISymbol symbol) => symbol == null ? null : CodeAnalysis.CSharp.SymbolDisplay.ToDisplayString(symbol, SymbolDisplayFormat.MinimallyQualifiedFormat); private async Task<ImmutableArray<SymbolDisplayPart>> GetInitializerSourcePartsAsync( IFieldSymbol symbol) { EqualsValueClauseSyntax initializer = null; var variableDeclarator = await GetFirstDeclarationAsync<VariableDeclaratorSyntax>(symbol).ConfigureAwait(false); if (variableDeclarator != null) { initializer = variableDeclarator.Initializer; } if (initializer == null) { var enumMemberDeclaration = await GetFirstDeclarationAsync<EnumMemberDeclarationSyntax>(symbol).ConfigureAwait(false); if (enumMemberDeclaration != null) { initializer = enumMemberDeclaration.EqualsValue; } } if (initializer != null) { return await GetInitializerSourcePartsAsync(initializer).ConfigureAwait(false); } return ImmutableArray<SymbolDisplayPart>.Empty; } private async Task<ImmutableArray<SymbolDisplayPart>> GetInitializerSourcePartsAsync( ILocalSymbol symbol) { var syntax = await GetFirstDeclarationAsync<VariableDeclaratorSyntax>(symbol).ConfigureAwait(false); if (syntax != null) { return await GetInitializerSourcePartsAsync(syntax.Initializer).ConfigureAwait(false); } return ImmutableArray<SymbolDisplayPart>.Empty; } private async Task<ImmutableArray<SymbolDisplayPart>> GetInitializerSourcePartsAsync( IParameterSymbol symbol) { var syntax = await GetFirstDeclarationAsync<ParameterSyntax>(symbol).ConfigureAwait(false); if (syntax != null) { return await GetInitializerSourcePartsAsync(syntax.Default).ConfigureAwait(false); } return ImmutableArray<SymbolDisplayPart>.Empty; } private async Task<T> GetFirstDeclarationAsync<T>(ISymbol symbol) where T : SyntaxNode { foreach (var syntaxRef in symbol.DeclaringSyntaxReferences) { var syntax = await syntaxRef.GetSyntaxAsync(CancellationToken).ConfigureAwait(false); if (syntax is T tSyntax) { return tSyntax; } } return null; } private async Task<ImmutableArray<SymbolDisplayPart>> GetInitializerSourcePartsAsync( EqualsValueClauseSyntax equalsValue) { if (equalsValue != null && equalsValue.Value != null) { var semanticModel = GetSemanticModel(equalsValue.SyntaxTree); if (semanticModel != null) { return await Classifier.GetClassifiedSymbolDisplayPartsAsync( semanticModel, equalsValue.Value.Span, Workspace, cancellationToken: CancellationToken).ConfigureAwait(false); } } return ImmutableArray<SymbolDisplayPart>.Empty; } protected override void AddCaptures(ISymbol symbol) { if (symbol is IMethodSymbol method && method.ContainingSymbol.IsKind(SymbolKind.Method)) { var syntax = method.DeclaringSyntaxReferences.FirstOrDefault()?.GetSyntax(); if (syntax.IsKind(SyntaxKind.LocalFunctionStatement) || syntax is AnonymousFunctionExpressionSyntax) { AddCaptures(syntax); } } } protected override SymbolDisplayFormat MinimallyQualifiedFormat => s_minimallyQualifiedFormat; protected override SymbolDisplayFormat MinimallyQualifiedFormatWithConstants => s_minimallyQualifiedFormatWithConstants; protected override SymbolDisplayFormat MinimallyQualifiedFormatWithConstantsAndModifiers => s_minimallyQualifiedFormatWithConstantsAndModifiers; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.CSharp.LanguageServices { internal partial class CSharpSymbolDisplayService { protected class SymbolDescriptionBuilder : AbstractSymbolDescriptionBuilder { private static readonly SymbolDisplayFormat s_minimallyQualifiedFormat = SymbolDisplayFormat.MinimallyQualifiedFormat .AddLocalOptions(SymbolDisplayLocalOptions.IncludeRef) .AddMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.UseErrorTypeSymbolName) .RemoveParameterOptions(SymbolDisplayParameterOptions.IncludeDefaultValue) .WithKindOptions(SymbolDisplayKindOptions.None); private static readonly SymbolDisplayFormat s_minimallyQualifiedFormatWithConstants = s_minimallyQualifiedFormat .AddLocalOptions(SymbolDisplayLocalOptions.IncludeConstantValue) .AddMemberOptions(SymbolDisplayMemberOptions.IncludeConstantValue) .AddParameterOptions(SymbolDisplayParameterOptions.IncludeDefaultValue); private static readonly SymbolDisplayFormat s_minimallyQualifiedFormatWithConstantsAndModifiers = s_minimallyQualifiedFormatWithConstants .AddMemberOptions(SymbolDisplayMemberOptions.IncludeModifiers); public SymbolDescriptionBuilder( SemanticModel semanticModel, int position, Workspace workspace, IAnonymousTypeDisplayService anonymousTypeDisplayService, CancellationToken cancellationToken) : base(semanticModel, position, workspace, anonymousTypeDisplayService, cancellationToken) { } protected override void AddDeprecatedPrefix() { AddToGroup(SymbolDescriptionGroups.MainDescription, Punctuation("["), PlainText(CSharpFeaturesResources.deprecated), Punctuation("]"), Space()); } protected override void AddExtensionPrefix() { AddToGroup(SymbolDescriptionGroups.MainDescription, Punctuation("("), PlainText(CSharpFeaturesResources.extension), Punctuation(")"), Space()); } protected override void AddAwaitablePrefix() { AddToGroup(SymbolDescriptionGroups.MainDescription, Punctuation("("), PlainText(CSharpFeaturesResources.awaitable), Punctuation(")"), Space()); } protected override void AddAwaitableExtensionPrefix() { AddToGroup(SymbolDescriptionGroups.MainDescription, Punctuation("("), PlainText(CSharpFeaturesResources.awaitable_extension), Punctuation(")"), Space()); } protected override void AddEnumUnderlyingTypeSeparator() { AddToGroup(SymbolDescriptionGroups.MainDescription, Space(), Punctuation(":"), Space()); } protected override Task<ImmutableArray<SymbolDisplayPart>> GetInitializerSourcePartsAsync( ISymbol symbol) { // Actually check for C# symbol types here. if (symbol is IParameterSymbol parameter) { return GetInitializerSourcePartsAsync(parameter); } else if (symbol is ILocalSymbol local) { return GetInitializerSourcePartsAsync(local); } else if (symbol is IFieldSymbol field) { return GetInitializerSourcePartsAsync(field); } return SpecializedTasks.EmptyImmutableArray<SymbolDisplayPart>(); } protected override ImmutableArray<SymbolDisplayPart> ToMinimalDisplayParts(ISymbol symbol, SemanticModel semanticModel, int position, SymbolDisplayFormat format) => CodeAnalysis.CSharp.SymbolDisplay.ToMinimalDisplayParts(symbol, semanticModel, position, format); protected override string GetNavigationHint(ISymbol symbol) => symbol == null ? null : CodeAnalysis.CSharp.SymbolDisplay.ToDisplayString(symbol, SymbolDisplayFormat.MinimallyQualifiedFormat); private async Task<ImmutableArray<SymbolDisplayPart>> GetInitializerSourcePartsAsync( IFieldSymbol symbol) { EqualsValueClauseSyntax initializer = null; var variableDeclarator = await GetFirstDeclarationAsync<VariableDeclaratorSyntax>(symbol).ConfigureAwait(false); if (variableDeclarator != null) { initializer = variableDeclarator.Initializer; } if (initializer == null) { var enumMemberDeclaration = await GetFirstDeclarationAsync<EnumMemberDeclarationSyntax>(symbol).ConfigureAwait(false); if (enumMemberDeclaration != null) { initializer = enumMemberDeclaration.EqualsValue; } } if (initializer != null) { return await GetInitializerSourcePartsAsync(initializer).ConfigureAwait(false); } return ImmutableArray<SymbolDisplayPart>.Empty; } private async Task<ImmutableArray<SymbolDisplayPart>> GetInitializerSourcePartsAsync( ILocalSymbol symbol) { var syntax = await GetFirstDeclarationAsync<VariableDeclaratorSyntax>(symbol).ConfigureAwait(false); if (syntax != null) { return await GetInitializerSourcePartsAsync(syntax.Initializer).ConfigureAwait(false); } return ImmutableArray<SymbolDisplayPart>.Empty; } private async Task<ImmutableArray<SymbolDisplayPart>> GetInitializerSourcePartsAsync( IParameterSymbol symbol) { var syntax = await GetFirstDeclarationAsync<ParameterSyntax>(symbol).ConfigureAwait(false); if (syntax != null) { return await GetInitializerSourcePartsAsync(syntax.Default).ConfigureAwait(false); } return ImmutableArray<SymbolDisplayPart>.Empty; } private async Task<T> GetFirstDeclarationAsync<T>(ISymbol symbol) where T : SyntaxNode { foreach (var syntaxRef in symbol.DeclaringSyntaxReferences) { var syntax = await syntaxRef.GetSyntaxAsync(CancellationToken).ConfigureAwait(false); if (syntax is T tSyntax) { return tSyntax; } } return null; } private async Task<ImmutableArray<SymbolDisplayPart>> GetInitializerSourcePartsAsync( EqualsValueClauseSyntax equalsValue) { if (equalsValue != null && equalsValue.Value != null) { var semanticModel = GetSemanticModel(equalsValue.SyntaxTree); if (semanticModel != null) { return await Classifier.GetClassifiedSymbolDisplayPartsAsync( semanticModel, equalsValue.Value.Span, Workspace, cancellationToken: CancellationToken).ConfigureAwait(false); } } return ImmutableArray<SymbolDisplayPart>.Empty; } protected override void AddCaptures(ISymbol symbol) { if (symbol is IMethodSymbol method && method.ContainingSymbol.IsKind(SymbolKind.Method)) { var syntax = method.DeclaringSyntaxReferences.FirstOrDefault()?.GetSyntax(); if (syntax.IsKind(SyntaxKind.LocalFunctionStatement) || syntax is AnonymousFunctionExpressionSyntax) { AddCaptures(syntax); } } } protected override SymbolDisplayFormat MinimallyQualifiedFormat => s_minimallyQualifiedFormat; protected override SymbolDisplayFormat MinimallyQualifiedFormatWithConstants => s_minimallyQualifiedFormatWithConstants; protected override SymbolDisplayFormat MinimallyQualifiedFormatWithConstantsAndModifiers => s_minimallyQualifiedFormatWithConstantsAndModifiers; } } }
-1
dotnet/roslyn
56,310
Move semantic classification caching down to Editor layer
CyrusNajmabadi
"2021-09-09T23:15:16Z"
"2021-09-10T19:26:25Z"
6e123012d868c56aba8acabfe1ccad1bf8f20b04
7af13b6e3867198cd59c566a905b332888ea1dec
Move semantic classification caching down to Editor layer.
./src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/DkmVendorId.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable #region Assembly Microsoft.VisualStudio.Debugger.Engine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a // References\Debugger\v2.0\Microsoft.VisualStudio.Debugger.Engine.dll #endregion using System; namespace Microsoft.VisualStudio.Debugger.Evaluation { public static class DkmVendorId { public static Guid Microsoft { get { return new Guid("994B45C4-E6E9-11D2-903F-00C04FA302A1"); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable #region Assembly Microsoft.VisualStudio.Debugger.Engine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a // References\Debugger\v2.0\Microsoft.VisualStudio.Debugger.Engine.dll #endregion using System; namespace Microsoft.VisualStudio.Debugger.Evaluation { public static class DkmVendorId { public static Guid Microsoft { get { return new Guid("994B45C4-E6E9-11D2-903F-00C04FA302A1"); } } } }
-1
dotnet/roslyn
56,310
Move semantic classification caching down to Editor layer
CyrusNajmabadi
"2021-09-09T23:15:16Z"
"2021-09-10T19:26:25Z"
6e123012d868c56aba8acabfe1ccad1bf8f20b04
7af13b6e3867198cd59c566a905b332888ea1dec
Move semantic classification caching down to Editor layer.
./src/VisualStudio/Core/Impl/CodeModel/Collections/AttributeArgumentCollection.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections { [ComVisible(true)] [ComDefaultInterface(typeof(ICodeElements))] public sealed class AttributeArgumentCollection : AbstractCodeElementCollection { internal static EnvDTE.CodeElements Create( CodeModelState state, CodeAttribute parent) { var collection = new AttributeArgumentCollection(state, parent); return (EnvDTE.CodeElements)ComAggregate.CreateAggregatedObject(collection); } private AttributeArgumentCollection( CodeModelState state, CodeAttribute parent) : base(state, parent) { } private CodeAttribute ParentAttribute { get { return (CodeAttribute)Parent; } } private SyntaxNode LookupNode() => this.ParentAttribute.LookupNode(); protected override bool TryGetItemByIndex(int index, out EnvDTE.CodeElement element) { var node = LookupNode(); var attributeArgumentNodes = CodeModelService.GetAttributeArgumentNodes(node); if (index >= 0 && index < attributeArgumentNodes.Count()) { element = (EnvDTE.CodeElement)CodeAttributeArgument.Create(this.State, this.ParentAttribute, index); return true; } element = null; return false; } protected override bool TryGetItemByName(string name, out EnvDTE.CodeElement element) { var node = LookupNode(); var currentIndex = 0; foreach (var child in CodeModelService.GetAttributeArgumentNodes(node)) { var childName = CodeModelService.GetName(child); if (childName == name) { element = (EnvDTE.CodeElement)CodeAttributeArgument.Create(this.State, this.ParentAttribute, currentIndex); return true; } currentIndex++; } element = null; return false; } public override int Count { get { var node = LookupNode(); return CodeModelService.GetAttributeArgumentNodes(node).Count(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections { [ComVisible(true)] [ComDefaultInterface(typeof(ICodeElements))] public sealed class AttributeArgumentCollection : AbstractCodeElementCollection { internal static EnvDTE.CodeElements Create( CodeModelState state, CodeAttribute parent) { var collection = new AttributeArgumentCollection(state, parent); return (EnvDTE.CodeElements)ComAggregate.CreateAggregatedObject(collection); } private AttributeArgumentCollection( CodeModelState state, CodeAttribute parent) : base(state, parent) { } private CodeAttribute ParentAttribute { get { return (CodeAttribute)Parent; } } private SyntaxNode LookupNode() => this.ParentAttribute.LookupNode(); protected override bool TryGetItemByIndex(int index, out EnvDTE.CodeElement element) { var node = LookupNode(); var attributeArgumentNodes = CodeModelService.GetAttributeArgumentNodes(node); if (index >= 0 && index < attributeArgumentNodes.Count()) { element = (EnvDTE.CodeElement)CodeAttributeArgument.Create(this.State, this.ParentAttribute, index); return true; } element = null; return false; } protected override bool TryGetItemByName(string name, out EnvDTE.CodeElement element) { var node = LookupNode(); var currentIndex = 0; foreach (var child in CodeModelService.GetAttributeArgumentNodes(node)) { var childName = CodeModelService.GetName(child); if (childName == name) { element = (EnvDTE.CodeElement)CodeAttributeArgument.Create(this.State, this.ParentAttribute, currentIndex); return true; } currentIndex++; } element = null; return false; } public override int Count { get { var node = LookupNode(); return CodeModelService.GetAttributeArgumentNodes(node).Count(); } } } }
-1
dotnet/roslyn
56,310
Move semantic classification caching down to Editor layer
CyrusNajmabadi
"2021-09-09T23:15:16Z"
"2021-09-10T19:26:25Z"
6e123012d868c56aba8acabfe1ccad1bf8f20b04
7af13b6e3867198cd59c566a905b332888ea1dec
Move semantic classification caching down to Editor layer.
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Extensions/DirectiveSyntaxExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Runtime.CompilerServices; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.Extensions { internal static partial class DirectiveSyntaxExtensions { private static readonly ConditionalWeakTable<SyntaxNode, DirectiveInfo> s_rootToDirectiveInfo = new(); private static SyntaxNode GetAbsoluteRoot(this SyntaxNode node) { while (node != null && (node.Parent != null || node is StructuredTriviaSyntax)) { if (node.Parent != null) { node = node.Parent; } else { node = node.ParentTrivia.Token.Parent; } } return node; } private static DirectiveInfo GetDirectiveInfo(SyntaxNode node, CancellationToken cancellationToken) { var root = node.GetAbsoluteRoot(); var info = s_rootToDirectiveInfo.GetValue(root, r => { var directiveMap = new Dictionary<DirectiveTriviaSyntax, DirectiveTriviaSyntax>( DirectiveSyntaxEqualityComparer.Instance); var conditionalMap = new Dictionary<DirectiveTriviaSyntax, IReadOnlyList<DirectiveTriviaSyntax>>( DirectiveSyntaxEqualityComparer.Instance); var walker = new DirectiveWalker(directiveMap, conditionalMap, cancellationToken); walker.Visit(r); walker.Finish(); return new DirectiveInfo(directiveMap, conditionalMap, inactiveRegionLines: null); }); return info; } internal static DirectiveTriviaSyntax GetMatchingDirective(this DirectiveTriviaSyntax directive, CancellationToken cancellationToken) { if (directive == null) { throw new ArgumentNullException(nameof(directive)); } var directiveSyntaxMap = GetDirectiveInfo(directive, cancellationToken).DirectiveMap; directiveSyntaxMap.TryGetValue(directive, out var result); return result; } internal static IReadOnlyList<DirectiveTriviaSyntax> GetMatchingConditionalDirectives(this DirectiveTriviaSyntax directive, CancellationToken cancellationToken) { if (directive == null) { throw new ArgumentNullException(nameof(directive)); } var directiveConditionalMap = GetDirectiveInfo(directive, cancellationToken).ConditionalMap; directiveConditionalMap.TryGetValue(directive, out var result); return result; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.Extensions { internal static partial class DirectiveSyntaxExtensions { private static readonly ConditionalWeakTable<SyntaxNode, DirectiveInfo> s_rootToDirectiveInfo = new(); private static SyntaxNode GetAbsoluteRoot(this SyntaxNode node) { while (node != null && (node.Parent != null || node is StructuredTriviaSyntax)) { if (node.Parent != null) { node = node.Parent; } else { node = node.ParentTrivia.Token.Parent; } } return node; } private static DirectiveInfo GetDirectiveInfo(SyntaxNode node, CancellationToken cancellationToken) { var root = node.GetAbsoluteRoot(); var info = s_rootToDirectiveInfo.GetValue(root, r => { var directiveMap = new Dictionary<DirectiveTriviaSyntax, DirectiveTriviaSyntax>( DirectiveSyntaxEqualityComparer.Instance); var conditionalMap = new Dictionary<DirectiveTriviaSyntax, IReadOnlyList<DirectiveTriviaSyntax>>( DirectiveSyntaxEqualityComparer.Instance); var walker = new DirectiveWalker(directiveMap, conditionalMap, cancellationToken); walker.Visit(r); walker.Finish(); return new DirectiveInfo(directiveMap, conditionalMap, inactiveRegionLines: null); }); return info; } internal static DirectiveTriviaSyntax GetMatchingDirective(this DirectiveTriviaSyntax directive, CancellationToken cancellationToken) { if (directive == null) { throw new ArgumentNullException(nameof(directive)); } var directiveSyntaxMap = GetDirectiveInfo(directive, cancellationToken).DirectiveMap; directiveSyntaxMap.TryGetValue(directive, out var result); return result; } internal static IReadOnlyList<DirectiveTriviaSyntax> GetMatchingConditionalDirectives(this DirectiveTriviaSyntax directive, CancellationToken cancellationToken) { if (directive == null) { throw new ArgumentNullException(nameof(directive)); } var directiveConditionalMap = GetDirectiveInfo(directive, cancellationToken).ConditionalMap; directiveConditionalMap.TryGetValue(directive, out var result); return result; } } }
-1
dotnet/roslyn
56,310
Move semantic classification caching down to Editor layer
CyrusNajmabadi
"2021-09-09T23:15:16Z"
"2021-09-10T19:26:25Z"
6e123012d868c56aba8acabfe1ccad1bf8f20b04
7af13b6e3867198cd59c566a905b332888ea1dec
Move semantic classification caching down to Editor layer.
./src/Features/Core/Portable/CodeCleanup/ICodeCleanupService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Host; using Microsoft.CodeAnalysis.Shared.Utilities; namespace Microsoft.CodeAnalysis.CodeCleanup { internal interface ICodeCleanupService : ILanguageService { Task<Document> CleanupAsync(Document document, EnabledDiagnosticOptions enabledDiagnostics, IProgressTracker progressTracker, CancellationToken cancellationToken); EnabledDiagnosticOptions GetAllDiagnostics(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Host; using Microsoft.CodeAnalysis.Shared.Utilities; namespace Microsoft.CodeAnalysis.CodeCleanup { internal interface ICodeCleanupService : ILanguageService { Task<Document> CleanupAsync(Document document, EnabledDiagnosticOptions enabledDiagnostics, IProgressTracker progressTracker, CancellationToken cancellationToken); EnabledDiagnosticOptions GetAllDiagnostics(); } }
-1
dotnet/roslyn
56,310
Move semantic classification caching down to Editor layer
CyrusNajmabadi
"2021-09-09T23:15:16Z"
"2021-09-10T19:26:25Z"
6e123012d868c56aba8acabfe1ccad1bf8f20b04
7af13b6e3867198cd59c566a905b332888ea1dec
Move semantic classification caching down to Editor layer.
./src/VisualStudio/IntegrationTest/TestUtilities/TemporaryTextFile.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.IO; namespace Microsoft.VisualStudio.IntegrationTest.Utilities { /// <summary> /// Provides methods for supporting temporary files within Roslyn tests. /// </summary> public class TemporaryTextFile : IDisposable { private readonly string _fileName; private readonly string _content; private readonly string _path; public TemporaryTextFile(string fileName, string content) { _fileName = fileName; _content = content; _path = IntegrationHelper.CreateTemporaryPath(); FullName = Path.Combine(_path, _fileName); } public void Create() { IntegrationHelper.CreateDirectory(_path, deleteExisting: true); using (var stream = File.Create(FullName)) { } File.WriteAllText(FullName, _content); } public string FullName { get; } public void Dispose() { IntegrationHelper.DeleteDirectoryRecursively(_path); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.IO; namespace Microsoft.VisualStudio.IntegrationTest.Utilities { /// <summary> /// Provides methods for supporting temporary files within Roslyn tests. /// </summary> public class TemporaryTextFile : IDisposable { private readonly string _fileName; private readonly string _content; private readonly string _path; public TemporaryTextFile(string fileName, string content) { _fileName = fileName; _content = content; _path = IntegrationHelper.CreateTemporaryPath(); FullName = Path.Combine(_path, _fileName); } public void Create() { IntegrationHelper.CreateDirectory(_path, deleteExisting: true); using (var stream = File.Create(FullName)) { } File.WriteAllText(FullName, _content); } public string FullName { get; } public void Dispose() { IntegrationHelper.DeleteDirectoryRecursively(_path); } } }
-1
dotnet/roslyn
56,310
Move semantic classification caching down to Editor layer
CyrusNajmabadi
"2021-09-09T23:15:16Z"
"2021-09-10T19:26:25Z"
6e123012d868c56aba8acabfe1ccad1bf8f20b04
7af13b6e3867198cd59c566a905b332888ea1dec
Move semantic classification caching down to Editor layer.
./src/Compilers/CSharp/Portable/Binder/ConstantFieldsInProgressBinder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// This binder keeps track of the set of constant fields that are currently being evaluated /// so that the set can be passed into the next call to SourceFieldSymbol.ConstantValue (and /// its callers). /// </summary> internal sealed class ConstantFieldsInProgressBinder : Binder { private readonly ConstantFieldsInProgress _inProgress; internal ConstantFieldsInProgressBinder(ConstantFieldsInProgress inProgress, Binder next) : base(next, BinderFlags.FieldInitializer | next.Flags) { _inProgress = inProgress; } internal override ConstantFieldsInProgress ConstantFieldsInProgress { get { return _inProgress; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// This binder keeps track of the set of constant fields that are currently being evaluated /// so that the set can be passed into the next call to SourceFieldSymbol.ConstantValue (and /// its callers). /// </summary> internal sealed class ConstantFieldsInProgressBinder : Binder { private readonly ConstantFieldsInProgress _inProgress; internal ConstantFieldsInProgressBinder(ConstantFieldsInProgress inProgress, Binder next) : base(next, BinderFlags.FieldInitializer | next.Flags) { _inProgress = inProgress; } internal override ConstantFieldsInProgress ConstantFieldsInProgress { get { return _inProgress; } } } }
-1
dotnet/roslyn
56,310
Move semantic classification caching down to Editor layer
CyrusNajmabadi
"2021-09-09T23:15:16Z"
"2021-09-10T19:26:25Z"
6e123012d868c56aba8acabfe1ccad1bf8f20b04
7af13b6e3867198cd59c566a905b332888ea1dec
Move semantic classification caching down to Editor layer.
./src/Compilers/CSharp/Test/Symbol/Symbols/ConversionTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols { public class ConversionTests : CSharpTestBase { [Fact] public void Test1() { var mscorlibRef = TestMetadata.Net40.mscorlib; var compilation = CSharpCompilation.Create("Test", references: new MetadataReference[] { mscorlibRef }); var sys = compilation.GlobalNamespace.ChildNamespace("System"); Conversions c = new BuckStopsHereBinder(compilation).Conversions; var types = new TypeSymbol[] { sys.ChildType("Object"), sys.ChildType("String"), sys.ChildType("Array"), sys.ChildType("Int64"), sys.ChildType("UInt64"), sys.ChildType("Int32"), sys.ChildType("UInt32"), sys.ChildType("Int16"), sys.ChildType("UInt16"), sys.ChildType("SByte"), sys.ChildType("Byte"), sys.ChildType("Double"), sys.ChildType("Single"), sys.ChildType("Decimal"), sys.ChildType("Char"), sys.ChildType("Nullable", 1).Construct(sys.ChildType("Int64")), sys.ChildType("Nullable", 1).Construct(sys.ChildType("UInt64")), sys.ChildType("Nullable", 1).Construct(sys.ChildType("Int32")), sys.ChildType("Nullable", 1).Construct(sys.ChildType("UInt32")), sys.ChildType("Nullable", 1).Construct(sys.ChildType("Int16")), sys.ChildType("Nullable", 1).Construct(sys.ChildType("UInt16")), sys.ChildType("Nullable", 1).Construct(sys.ChildType("SByte")), sys.ChildType("Nullable", 1).Construct(sys.ChildType("Byte")), sys.ChildType("Nullable", 1).Construct(sys.ChildType("Double")), sys.ChildType("Nullable", 1).Construct(sys.ChildType("Single")), sys.ChildType("Nullable", 1).Construct(sys.ChildType("Decimal")), sys.ChildType("Nullable", 1).Construct(sys.ChildType("Char")), sys.ChildType("Exception"), sys.ChildNamespace("Collections").ChildType("IEnumerable"), sys.ChildNamespace("Collections").ChildNamespace("Generic").ChildType("IEnumerable", 1).Construct(sys.ChildType("Object")), sys.ChildNamespace("Collections").ChildNamespace("Generic").ChildType("IEnumerable", 1).Construct(sys.ChildType("String")), sys.ChildNamespace("Collections").ChildNamespace("Generic").ChildType("IEnumerable", 1).Construct(sys.ChildType("Char")), compilation.CreateArrayTypeSymbol(sys.ChildType("String")), compilation.CreateArrayTypeSymbol(sys.ChildType("Object")), sys.ChildNamespace("Collections").ChildNamespace("Generic").ChildType("IList", 1).Construct(sys.ChildType("String")), sys.ChildNamespace("Collections").ChildNamespace("Generic").ChildType("IList", 1).Construct(sys.ChildType("Object")), sys.ChildType("ArgumentException"), sys.ChildType("Delegate"), sys.ChildType("Func", 2).Construct(sys.ChildType("Exception"), sys.ChildType("Exception")), sys.ChildType("Func", 2).Construct(sys.ChildType("ArgumentException"), sys.ChildType("Object")), sys.ChildNamespace("Runtime").ChildNamespace("Serialization").ChildType("ISerializable"), sys.ChildType("IComparable", 0), }; const ConversionKind Non = ConversionKind.NoConversion; const ConversionKind Idn = ConversionKind.Identity; const ConversionKind Inm = ConversionKind.ImplicitNumeric; const ConversionKind Inl = ConversionKind.ImplicitNullable; const ConversionKind Irf = ConversionKind.ImplicitReference; const ConversionKind Box = ConversionKind.Boxing; const ConversionKind Xrf = ConversionKind.ExplicitReference; const ConversionKind Ubx = ConversionKind.Unboxing; const ConversionKind Xnl = ConversionKind.ExplicitNullable; const ConversionKind Xnm = ConversionKind.ExplicitNumeric; ConversionKind[,] conversions = { // from obj str arr i64 u64 i32 u32 i16 u16 i08 u08 r64 r32 dec chr ni64 nu64 ni32 nu32 ni16 nu16 ni8 nu8 nr64 nr32 ndc nch exc ien ieo ies iec ars aro ils ilo aex del fee fao ser cmp // to: /*obj*/ { Idn, Irf, Irf, Box, Box, Box, Box, Box, Box, Box, Box, Box, Box, Box, Box, Box, Box, Box, Box, Box, Box, Box, Box, Box, Box, Box, Box, Irf, Irf, Irf, Irf, Irf, Irf, Irf, Irf, Irf, Irf, Irf, Irf, Irf, Irf, Irf }, /*str*/ { Xrf, Idn, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Xrf, Non, Non, Xrf, Non, Non, Non, Non, Non, Non, Non, Non, Non, Xrf }, /*arr*/ { Xrf, Non, Idn, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Xrf, Xrf, Xrf, Xrf, Irf, Irf, Xrf, Xrf, Non, Non, Non, Non, Xrf, Xrf }, /*i64*/ { Ubx, Non, Non, Idn, Xnm, Inm, Inm, Inm, Inm, Inm, Inm, Xnm, Xnm, Xnm, Inm, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Ubx }, /*u64*/ { Ubx, Non, Non, Xnm, Idn, Xnm, Inm, Xnm, Inm, Xnm, Inm, Xnm, Xnm, Xnm, Inm, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Ubx }, /*i32*/ { Ubx, Non, Non, Xnm, Xnm, Idn, Xnm, Inm, Inm, Inm, Inm, Xnm, Xnm, Xnm, Inm, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Ubx }, /*u32*/ { Ubx, Non, Non, Xnm, Xnm, Xnm, Idn, Xnm, Inm, Xnm, Inm, Xnm, Xnm, Xnm, Inm, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Ubx }, /*i16*/ { Ubx, Non, Non, Xnm, Xnm, Xnm, Xnm, Idn, Xnm, Inm, Inm, Xnm, Xnm, Xnm, Xnm, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Ubx }, /*u16*/ { Ubx, Non, Non, Xnm, Xnm, Xnm, Xnm, Xnm, Idn, Xnm, Inm, Xnm, Xnm, Xnm, Inm, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Ubx }, /*i08*/ { Ubx, Non, Non, Xnm, Xnm, Xnm, Xnm, Xnm, Xnm, Idn, Xnm, Xnm, Xnm, Xnm, Xnm, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Ubx }, /*u08*/ { Ubx, Non, Non, Xnm, Xnm, Xnm, Xnm, Xnm, Xnm, Xnm, Idn, Xnm, Xnm, Xnm, Xnm, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Ubx }, /*r64*/ { Ubx, Non, Non, Inm, Inm, Inm, Inm, Inm, Inm, Inm, Inm, Idn, Inm, Xnm, Inm, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Ubx }, /*r32*/ { Ubx, Non, Non, Inm, Inm, Inm, Inm, Inm, Inm, Inm, Inm, Xnm, Idn, Xnm, Inm, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Ubx }, /*dec*/ { Ubx, Non, Non, Inm, Inm, Inm, Inm, Inm, Inm, Inm, Inm, Xnm, Xnm, Idn, Inm, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Ubx }, /*chr*/ { Ubx, Non, Non, Xnm, Xnm, Xnm, Xnm, Xnm, Xnm, Xnm, Xnm, Xnm, Xnm, Xnm, Idn, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Ubx }, /*ni64*/ { Ubx, Non, Non, Inl, Xnl, Inl, Inl, Inl, Inl, Inl, Inl, Xnl, Xnl, Xnl, Inl, Idn, Xnl, Inl, Inl, Inl, Inl, Inl, Inl, Xnl, Xnl, Xnl, Inl, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Ubx }, /*nu64*/ { Ubx, Non, Non, Xnl, Inl, Xnl, Inl, Xnl, Inl, Xnl, Inl, Xnl, Xnl, Xnl, Inl, Xnl, Idn, Xnl, Inl, Xnl, Inl, Xnl, Inl, Xnl, Xnl, Xnl, Inl, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Ubx }, /*ni32*/ { Ubx, Non, Non, Xnl, Xnl, Inl, Xnl, Inl, Inl, Inl, Inl, Xnl, Xnl, Xnl, Inl, Xnl, Xnl, Idn, Xnl, Inl, Inl, Inl, Inl, Xnl, Xnl, Xnl, Inl, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Ubx }, /*nu32*/ { Ubx, Non, Non, Xnl, Xnl, Xnl, Inl, Xnl, Inl, Xnl, Inl, Xnl, Xnl, Xnl, Inl, Xnl, Xnl, Xnl, Idn, Xnl, Inl, Xnl, Inl, Xnl, Xnl, Xnl, Inl, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Ubx }, /*ni16*/ { Ubx, Non, Non, Xnl, Xnl, Xnl, Xnl, Inl, Xnl, Inl, Inl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Idn, Xnl, Inl, Inl, Xnl, Xnl, Xnl, Xnl, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Ubx }, /*nu16*/ { Ubx, Non, Non, Xnl, Xnl, Xnl, Xnl, Xnl, Inl, Xnl, Inl, Xnl, Xnl, Xnl, Inl, Xnl, Xnl, Xnl, Xnl, Xnl, Idn, Xnl, Inl, Xnl, Xnl, Xnl, Inl, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Ubx }, /*ni8*/ { Ubx, Non, Non, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Inl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Idn, Xnl, Xnl, Xnl, Xnl, Xnl, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Ubx }, /*nu8*/ { Ubx, Non, Non, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Inl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Idn, Xnl, Xnl, Xnl, Xnl, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Ubx }, /*nr64*/ { Ubx, Non, Non, Inl, Inl, Inl, Inl, Inl, Inl, Inl, Inl, Inl, Inl, Xnl, Inl, Inl, Inl, Inl, Inl, Inl, Inl, Inl, Inl, Idn, Inl, Xnl, Inl, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Ubx }, /*nr32*/ { Ubx, Non, Non, Inl, Inl, Inl, Inl, Inl, Inl, Inl, Inl, Xnl, Inl, Xnl, Inl, Inl, Inl, Inl, Inl, Inl, Inl, Inl, Inl, Xnl, Idn, Xnl, Inl, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Ubx }, /*ndc*/ { Ubx, Non, Non, Inl, Inl, Inl, Inl, Inl, Inl, Inl, Inl, Xnl, Xnl, Inl, Inl, Inl, Inl, Inl, Inl, Inl, Inl, Inl, Inl, Xnl, Xnl, Idn, Inl, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Ubx }, /*nch*/ { Ubx, Non, Non, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Inl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Idn, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Ubx }, /*exc*/ { Xrf, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Idn, Xrf, Xrf, Xrf, Xrf, Non, Non, Xrf, Xrf, Irf, Non, Non, Non, Xrf, Xrf }, /*ien*/ { Xrf, Irf, Irf, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Xrf, Idn, Irf, Irf, Irf, Irf, Irf, Irf, Irf, Xrf, Xrf, Non, Non, Xrf, Xrf }, /*ieo*/ { Xrf, Non, Xrf, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Xrf, Xrf, Idn, Irf, Xrf, Irf, Irf, Irf, Irf, Xrf, Xrf, Non, Non, Xrf, Xrf }, /*ies*/ { Xrf, Non, Xrf, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Xrf, Xrf, Xrf, Idn, Xrf, Irf, Xrf, Irf, Xrf, Xrf, Xrf, Non, Non, Xrf, Xrf }, /*iec*/ { Xrf, Irf, Xrf, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Xrf, Xrf, Xrf, Xrf, Idn, Non, Non, Xrf, Xrf, Xrf, Xrf, Non, Non, Xrf, Xrf }, /*ars*/ { Xrf, Non, Xrf, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Xrf, Xrf, Xrf, Non, Idn, Xrf, Xrf, Xrf, Non, Non, Non, Non, Non, Non }, /*aro*/ { Xrf, Non, Xrf, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Xrf, Xrf, Xrf, Non, Irf, Idn, Xrf, Xrf, Non, Non, Non, Non, Non, Non }, /*ils*/ { Xrf, Non, Xrf, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Xrf, Xrf, Xrf, Xrf, Xrf, Irf, Xrf, Idn, Xrf, Xrf, Xrf, Non, Non, Xrf, Xrf }, /*ilo*/ { Xrf, Non, Xrf, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Xrf, Xrf, Xrf, Xrf, Xrf, Irf, Irf, Xrf, Idn, Xrf, Xrf, Non, Non, Xrf, Xrf }, /*aex*/ { Xrf, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Xrf, Xrf, Xrf, Xrf, Xrf, Non, Non, Xrf, Xrf, Idn, Non, Non, Non, Xrf, Xrf }, /*del*/ { Xrf, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Xrf, Xrf, Xrf, Xrf, Non, Non, Xrf, Xrf, Non, Idn, Irf, Irf, Xrf, Xrf }, /*fee*/ { Xrf, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Xrf, Idn, Xrf, Xrf, Non }, /*fao*/ { Xrf, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Xrf, Irf, Idn, Xrf, Non }, /*ser*/ { Xrf, Non, Xrf, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Irf, Xrf, Xrf, Xrf, Xrf, Non, Non, Xrf, Xrf, Irf, Irf, Irf, Irf, Idn, Xrf }, /*cmp*/ { Xrf, Irf, Xrf, Box, Box, Box, Box, Box, Box, Box, Box, Box, Box, Box, Box, Box, Box, Box, Box, Box, Box, Box, Box, Box, Box, Box, Box, Xrf, Xrf, Xrf, Xrf, Xrf, Non, Non, Xrf, Xrf, Xrf, Xrf, Non, Non, Xrf, Idn }, }; HashSet<DiagnosticInfo> useSiteDiagnostics = null; for (int i = 0; i < types.Length; ++i) { for (int j = 0; j < types.Length; ++j) { var kind = conversions[i, j]; var result = c.ClassifyConversionFromType(types[j], types[i], ref useSiteDiagnostics); //Assert.Equal doesn't allow a string explanation, so provide one this way. if (kind != result.Kind) { var result2 = c.ClassifyConversionFromType(types[j], types[i], ref useSiteDiagnostics); // set breakpoint here if this test is failing... Assert.True(false, string.Format("Expected {0} but got {1} when converting {2} -> {3}", kind, result, types[j], types[i])); } } } // UNDONE: Not tested yet: // UNDONE: Type parameter reference, boxing and unboxing conversions // UNDONE: User-defined conversions // UNDONE: Dynamic conversions // UNDONE: Enum conversions // UNDONE: Conversions involving expressions: null, lambda, method group } [Fact] public void TestIsSameTypeIgnoringDynamic() { string code = @" class O<T> { public class I<U,V> { static O<object>.I<U,V> g1; static O<dynamic>.I<U,V> g2; } } class X { object f1; dynamic f2; object[] f3; dynamic[] f4; object[,] f5; O<object>.I<int, object> f6; O<dynamic>.I<int, object> f7; O<object>.I<int, dynamic> f8; O<string> f9; O<dynamic> f10; } "; var mscorlibRef = TestMetadata.Net40.mscorlib; var compilation = CSharpCompilation.Create("Test", new[] { Parse(code) }, new[] { mscorlibRef }); var global = compilation.GlobalNamespace; var classX = global.ChildType("X"); var classI = (NamedTypeSymbol)(global.ChildType("O").ChildSymbol("I")); var f1Type = ((FieldSymbol)(classX.ChildSymbol("f1"))).Type; var f2Type = ((FieldSymbol)(classX.ChildSymbol("f2"))).Type; var f3Type = ((FieldSymbol)(classX.ChildSymbol("f3"))).Type; var f4Type = ((FieldSymbol)(classX.ChildSymbol("f4"))).Type; var f5Type = ((FieldSymbol)(classX.ChildSymbol("f5"))).Type; var f6Type = ((FieldSymbol)(classX.ChildSymbol("f6"))).Type; var f7Type = ((FieldSymbol)(classX.ChildSymbol("f7"))).Type; var f8Type = ((FieldSymbol)(classX.ChildSymbol("f8"))).Type; var f9Type = ((FieldSymbol)(classX.ChildSymbol("f9"))).Type; var f10Type = ((FieldSymbol)(classX.ChildSymbol("f10"))).Type; var g1Type = ((FieldSymbol)(classI.ChildSymbol("g1"))).Type; var g2Type = ((FieldSymbol)(classI.ChildSymbol("g2"))).Type; string s = f7Type.ToTestDisplayString(); Assert.False(f1Type.Equals(f2Type)); Assert.True(f1Type.Equals(f2Type, TypeCompareKind.AllIgnoreOptions)); Assert.True(f2Type.Equals(f1Type, TypeCompareKind.AllIgnoreOptions)); Assert.True(f1Type.Equals(f1Type, TypeCompareKind.AllIgnoreOptions)); Assert.True(f2Type.Equals(f2Type, TypeCompareKind.AllIgnoreOptions)); Assert.False(f3Type.Equals(f4Type)); Assert.True(f3Type.Equals(f4Type, TypeCompareKind.AllIgnoreOptions)); Assert.True(f4Type.Equals(f3Type, TypeCompareKind.AllIgnoreOptions)); Assert.False(f4Type.Equals(f5Type, TypeCompareKind.AllIgnoreOptions)); Assert.False(f5Type.Equals(f4Type, TypeCompareKind.AllIgnoreOptions)); Assert.False(f6Type.Equals(f7Type)); Assert.False(f6Type.Equals(f8Type)); Assert.False(f7Type.Equals(f8Type)); Assert.True(f6Type.Equals(f7Type, TypeCompareKind.AllIgnoreOptions)); Assert.True(f7Type.Equals(f6Type, TypeCompareKind.AllIgnoreOptions)); Assert.True(f6Type.Equals(f6Type, TypeCompareKind.AllIgnoreOptions)); Assert.True(f7Type.Equals(f7Type, TypeCompareKind.AllIgnoreOptions)); Assert.True(f8Type.Equals(f7Type, TypeCompareKind.AllIgnoreOptions)); Assert.True(f7Type.Equals(f8Type, TypeCompareKind.AllIgnoreOptions)); Assert.True(f8Type.Equals(f8Type, TypeCompareKind.AllIgnoreOptions)); Assert.True(f7Type.Equals(f7Type, TypeCompareKind.AllIgnoreOptions)); Assert.True(f8Type.Equals(f6Type, TypeCompareKind.AllIgnoreOptions)); Assert.True(f6Type.Equals(f8Type, TypeCompareKind.AllIgnoreOptions)); Assert.True(f8Type.Equals(f8Type, TypeCompareKind.AllIgnoreOptions)); Assert.True(f6Type.Equals(f6Type, TypeCompareKind.AllIgnoreOptions)); Assert.False(f9Type.Equals(f10Type, TypeCompareKind.AllIgnoreOptions)); Assert.False(f10Type.Equals(f9Type, TypeCompareKind.AllIgnoreOptions)); Assert.False(g1Type.Equals(g2Type)); Assert.True(g1Type.Equals(g2Type, TypeCompareKind.AllIgnoreOptions)); Assert.True(g2Type.Equals(g1Type, TypeCompareKind.AllIgnoreOptions)); Assert.True(g1Type.Equals(g1Type, TypeCompareKind.AllIgnoreOptions)); Assert.True(g2Type.Equals(g2Type, TypeCompareKind.AllIgnoreOptions)); } /// <summary> /// ClassifyConversions should ignore custom modifiers: converting between a type and the same type /// with different custom modifiers should be an identity conversion. /// </summary> [Fact] public void TestConversionsWithCustomModifiers() { var text = @" class C { int[] a; } "; var ilAssemblyReference = TestReferences.SymbolsTests.CustomModifiers.Modifiers.dll; var compilation = CreateCompilation(text, new MetadataReference[] { ilAssemblyReference }); compilation.VerifyDiagnostics( // (4,11): warning CS0169: The field 'C.a' is never used // int[] a; Diagnostic(ErrorCode.WRN_UnreferencedField, "a").WithArguments("C.a") ); var classC = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var typeIntArray = classC.GetMember<FieldSymbol>("a").Type; var interfaceI3 = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("I3"); var typeIntArrayWithCustomModifiers = interfaceI3.GetMember<MethodSymbol>("M1").Parameters.Single().Type; Assert.True(typeIntArrayWithCustomModifiers.HasCustomModifiers(flagNonDefaultArraySizesOrLowerBounds: false)); var conv = new BuckStopsHereBinder(compilation).Conversions; HashSet<DiagnosticInfo> useSiteDiagnostics = null; // no custom modifiers to custom modifiers Assert.Equal(ConversionKind.Identity, conv.ClassifyConversionFromType(typeIntArray, typeIntArrayWithCustomModifiers, ref useSiteDiagnostics).Kind); // custom modifiers to no custom modifiers Assert.Equal(ConversionKind.Identity, conv.ClassifyConversionFromType(typeIntArrayWithCustomModifiers, typeIntArray, ref useSiteDiagnostics).Kind); // custom modifiers to custom modifiers Assert.Equal(ConversionKind.Identity, conv.ClassifyConversionFromType(typeIntArrayWithCustomModifiers, typeIntArrayWithCustomModifiers, ref useSiteDiagnostics).Kind); } [WorkItem(529056, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529056")] [WorkItem(529056, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529056")] [Fact()] public void TestConversion_ParenthesizedExpression() { var source = @" using System; public class Program { public static bool Eval(object obj1, object obj2) { if (/*<bind>*/(obj1 != null)/*</bind>*/ && (obj2 != null)) { return true; } return false; } } "; var comp = (Compilation)CreateCompilation(source); var tuple = GetBindingNodeAndModel<ExpressionSyntax>(comp); Assert.Equal(ConversionKind.Identity, tuple.Item2.ClassifyConversion(tuple.Item1, comp.GetSpecialType(SpecialType.System_Boolean)).Kind); } [WorkItem(544571, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544571")] [Fact] public void TestClassifyConversion() { var source = @" using System; class Program { static void M() { } static void M(long l) { } static void M(short s) { } static void M(int i) { } static void Main() { int ii = 0; Console.WriteLine(ii); short jj = 1; Console.WriteLine(jj); string ss = string.Empty; Console.WriteLine(ss); // Perform conversion classification here. } }"; var tree = SyntaxFactory.ParseSyntaxTree(source); var compilation = (Compilation)CSharpCompilation.Create("MyCompilation") .AddReferences(MscorlibRef) .AddSyntaxTrees(tree); var model = compilation.GetSemanticModel(tree); // Get VariableDeclaratorSyntax corresponding to variable 'ii' above. var variableDeclarator = (VariableDeclaratorSyntax)tree.GetCompilationUnitRoot() .FindToken(source.IndexOf("ii", StringComparison.Ordinal)).Parent; // Get TypeSymbol corresponding to above VariableDeclaratorSyntax. ITypeSymbol targetType = ((ILocalSymbol)model.GetDeclaredSymbol(variableDeclarator)).Type; // Perform ClassifyConversion for expressions from within the above SyntaxTree. var sourceExpression1 = (ExpressionSyntax)tree.GetCompilationUnitRoot() .FindToken(source.IndexOf("jj)", StringComparison.Ordinal)).Parent; Conversion conversion = model.ClassifyConversion(sourceExpression1, targetType); Assert.True(conversion.IsImplicit); Assert.True(conversion.IsNumeric); var sourceExpression2 = (ExpressionSyntax)tree.GetCompilationUnitRoot() .FindToken(source.IndexOf("ss)", StringComparison.Ordinal)).Parent; conversion = model.ClassifyConversion(sourceExpression2, targetType); Assert.False(conversion.Exists); // Perform ClassifyConversion for constructed expressions // at the position identified by the comment '// Perform ...' above. ExpressionSyntax sourceExpression3 = SyntaxFactory.IdentifierName("jj"); var position = source.IndexOf("//", StringComparison.Ordinal); conversion = model.ClassifyConversion(position, sourceExpression3, targetType); Assert.True(conversion.IsImplicit); Assert.True(conversion.IsNumeric); ExpressionSyntax sourceExpression4 = SyntaxFactory.IdentifierName("ss"); conversion = model.ClassifyConversion(position, sourceExpression4, targetType); Assert.False(conversion.Exists); ExpressionSyntax sourceExpression5 = SyntaxFactory.ParseExpression("100L"); conversion = model.ClassifyConversion(position, sourceExpression5, targetType); Assert.True(conversion.IsExplicit); Assert.True(conversion.IsNumeric); } #region "Diagnostics" [Fact] public void VarianceRelationFail() { var source = @" delegate void Covariant<out T>(int argument); class B { } class C { } class Program { public static void Main(string[] args) { Covariant<B> cb = null; Covariant<C> cc = (Covariant<C>)cb; } } "; var compilation = CreateCompilation(source); var diagnostics = compilation.GetDiagnostics(); Assert.NotEmpty(diagnostics); } [Fact] public void EnumFromZero() { var source = @" enum Enum { e1, e2 }; class Program { public static void Main(string[] args) { Enum e = (12L - 12); e = e + 1; } } "; var compilation = CreateCompilation(source); var diagnostics = compilation.GetDiagnostics(); Assert.Empty(diagnostics); } [Fact] public void IdentityConversionInvolvingDynamic() { var source = @" interface I1<T> { } interface I2<T, U> { } class Program { public static void Main(string[] args) { I2<I1<dynamic>, I1<object>> i1 = null; I2<I1<object>, I1<dynamic>> i2 = null; i1 = i2; i2 = i1; } } "; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void WrongDirectionVarianceValueType() { var source = @" interface I<out T> { } struct S : I<object> { public void M() { } } class Program { public static void Main(string[] args) { I<string> i = null; S s = (S)i; } } "; var compilation = CreateCompilation(source); var diagnostics = compilation.GetDiagnostics(); Assert.NotEmpty(diagnostics); } [Fact] public void CastInterfaceToNonimplementingSealed() { var source = @" interface I1 {} sealed class C1 {} public class Driver { public static void Main() { I1 inter = null; C1 c1 = (C1)inter; } } "; var compilation = CreateCompilation(source); var diagnostics = compilation.GetDiagnostics(); Assert.NotEmpty(diagnostics); } [Fact] public void TestLiteralZeroToNullableEnumConversion() { // Oddly enough, the C# specification categorizes // the conversion from 0 to E? as an implicit enumeration conversion, // not as a nullable conversion. var source = @" class Program { enum E { None } public static void Main() { E? e = 0; System.Console.WriteLine(e); } } "; CreateCompilation(source).VerifyDiagnostics(); } [WorkItem(542540, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542540")] [Fact] public void TestMethodGroupConversionWithOptionalParameter() { var source = @" class C { static void goo(int x = 0) //overload resolution picks this method, but the parameter count doesn't match { System.Action a = goo; } } "; CreateCompilation(source).VerifyDiagnostics( // (6,27): error CS0123: No overload for 'goo' matches delegate 'System.Action' // System.Action a = goo; Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "goo").WithArguments("goo", "System.Action")); } [WorkItem(543119, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543119")] [Fact] public void TestConversion_IntToNullableShort() { var source = @"namespace Test { public class Program { short? Goo() { short? s = 2; return s; } } }"; CreateCompilation(source).VerifyDiagnostics(); } [WorkItem(543450, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543450")] [Fact()] public void TestConversion_IntToByte() { var source = @" class Program { public static void Main() { byte x = 1; int y = 1; x <<= y; } }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void AmbiguousImplicitConversion() { var source = @" public class A { static public implicit operator A(B b) { return default(A); } } public class B { static public implicit operator A(B b) { return default(A); } } class Test { static void Main() { B b = new B(); A a = b; } }"; CreateCompilation(source).VerifyDiagnostics( // (23,15): error CS0457: Ambiguous user defined conversions 'B.implicit operator A(B)' and 'A.implicit operator A(B)' when converting from 'B' to 'A' Diagnostic(ErrorCode.ERR_AmbigUDConv, "b").WithArguments("B.implicit operator A(B)", "A.implicit operator A(B)", "B", "A")); } [Fact] public void AmbiguousImplicitConversionAsExplicit() { var source = @" public class A { static public implicit operator A(B b) { return default(A); } } public class B { static public implicit operator A(B b) { return default(A); } } class Test { static void Main() { B b = new B(); A a = (A)b; } }"; CreateCompilation(source).VerifyDiagnostics( // (23,15): error CS0457: Ambiguous user defined conversions 'B.implicit operator A(B)' and 'A.implicit operator A(B)' when converting from 'B' to 'A' Diagnostic(ErrorCode.ERR_AmbigUDConv, "(A)b").WithArguments("B.implicit operator A(B)", "A.implicit operator A(B)", "B", "A")); } [Fact] public void AmbiguousImplicitConversionGeneric() { var source = @" public class A { static public implicit operator A(B<A> b) { return default(A); } } public class B<T> { static public implicit operator T(B<T> b) { return default(T); } } class C { static void Main() { B<A> b = new B<A>(); A a = b; } }"; CreateCompilation(source).VerifyDiagnostics( // (23,15): error CS0457: Ambiguous user defined conversions 'B<A>.implicit operator A(B<A>)' and 'A.implicit operator A(B<A>)' when converting from 'B<A>' to 'A' Diagnostic(ErrorCode.ERR_AmbigUDConv, "b").WithArguments("B<A>.implicit operator A(B<A>)", "A.implicit operator A(B<A>)", "B<A>", "A")); } [Fact] public void AmbiguousExplicitConversion() { var source = @" public class A { static public explicit operator A(B b) { return default(A); } } public class B { static public explicit operator A(B b) { return default(A); } } class Test { static void Main() { B b = new B(); A a = (A)b; } }"; CreateCompilation(source).VerifyDiagnostics( // (23,15): error CS0457: Ambiguous user defined conversions 'B.explicit operator A(B)' and 'A.explicit operator A(B)' when converting from 'B' to 'A' Diagnostic(ErrorCode.ERR_AmbigUDConv, "(A)b").WithArguments("B.explicit operator A(B)", "A.explicit operator A(B)", "B", "A")); } [Fact] public void AmbiguousExplicitConversionAsImplicit() { var source = @" public class A { static public explicit operator A(B b) { return default(A); } } public class B { static public explicit operator A(B b) { return default(A); } } class Test { static void Main() { B b = new B(); A a = b; } }"; CreateCompilation(source).VerifyDiagnostics( // (23,15): error CS0266: Cannot implicitly convert type 'B' to 'A'. An explicit conversion exists (are you missing a cast?) Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "b").WithArguments("B", "A")); } [Fact] public void AmbiguousImplicitExplicitConversionAsImplicit() { var source = @" public class A { static public implicit operator A(B b) { return default(A); } } public class B { static public explicit operator A(B b) { return default(A); } } class Test { static void Main() { B b = new B(); A a = b; } }"; // As in Dev10, we prefer the implicit conversion. CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void AmbiguousImplicitExplicitConversionAsExplicit() { var source = @" public class A { static public implicit operator A(B b) { return default(A); } } public class B { static public explicit operator A(B b) { return default(A); } } class Test { static void Main() { B b = new B(); A a = (A)b; } }"; CreateCompilation(source).VerifyDiagnostics( // (23,15): error CS0457: Ambiguous user defined conversions 'B.explicit operator A(B)' and 'A.implicit operator A(B)' when converting from 'B' to 'A' // A a = (A)b; Diagnostic(ErrorCode.ERR_AmbigUDConv, "(A)b").WithArguments("B.explicit operator A(B)", "A.implicit operator A(B)", "B", "A")); } [Fact] public void NoImplicitConversionsDefaultParameter_01() { var source = @" class C { void Goo(float x = 0.0) { } }"; CreateCompilation(source).VerifyDiagnostics( // (4,20): error CS1750: A value of type 'double' cannot be used as a default parameter because there are no standard conversions to type 'float' // void Goo(float x = 0.0) Diagnostic(ErrorCode.ERR_NoConversionForDefaultParam, "x").WithArguments("double", "float").WithLocation(4, 20) ); } [Fact] public void NoUserDefinedConversionsDefaultParameter1() { var source = @" public class A { static public implicit operator int(A a) { throw null; } } class C { void Goo(int x = default(A)) { } }"; CreateCompilation(source).VerifyDiagnostics( // (12,18): error CS1750: A value of type 'A' cannot be used as a default parameter because there are no standard conversions to type 'int' Diagnostic(ErrorCode.ERR_NoConversionForDefaultParam, "x").WithArguments("A", "int")); } [Fact] public void NoUserDefinedConversionsDefaultParameter2() { var source = @" public class A { static public implicit operator A(int i) { throw null; } } class C { void Goo(A x = default(int)) { } }"; CreateCompilation(source).VerifyDiagnostics( // (12,16): error CS1750: A value of type 'int' cannot be used as a default parameter because there are no standard conversions to type 'A' Diagnostic(ErrorCode.ERR_NoConversionForDefaultParam, "x").WithArguments("int", "A")); } [Fact] public void NoUserDefinedConversionsDefaultParameter3() { var source = @" class Base { } class Derived : Base { } class A { static public implicit operator Derived(A a) { throw null; } } class C { void Goo(Base b = default(A)) { } }"; CreateCompilation(source).VerifyDiagnostics( // (15,19): error CS1750: A value of type 'A' cannot be used as a default parameter because there are no standard conversions to type 'Base' Diagnostic(ErrorCode.ERR_NoConversionForDefaultParam, "b").WithArguments("A", "Base")); } [Fact] public void NoUserDefinedConversionsIs() { var source = @" using System; public sealed class A { static public implicit operator A(B b) { throw null; } static public implicit operator B(A b) { throw null; } } public sealed class B { } class C { static void Main() { A a = new A(); B b = new B(); Console.WriteLine(a is B); Console.WriteLine(b is A); } }"; CreateCompilation(source).VerifyDiagnostics( // (27,27): warning CS0184: The given expression is never of the provided ('B') type Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "a is B").WithArguments("B"), // (28,27): warning CS0184: The given expression is never of the provided ('A') type Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "b is A").WithArguments("A")); } [Fact] public void NoUserDefinedConversionsAs() { var source = @" using System; public sealed class A { static public implicit operator A(B b) { throw null; } static public implicit operator B(A b) { throw null; } } public sealed class B { } class C { static void Main() { A a = new A(); B b = new B(); Console.WriteLine(a as B); Console.WriteLine(b as A); } }"; CreateCompilation(source).VerifyDiagnostics( // (27,27): error CS0039: Cannot convert type 'A' to 'B' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion Diagnostic(ErrorCode.ERR_NoExplicitBuiltinConv, "a as B").WithArguments("A", "B"), // (28,27): error CS0039: Cannot convert type 'B' to 'A' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion Diagnostic(ErrorCode.ERR_NoExplicitBuiltinConv, "b as A").WithArguments("B", "A")); } [Fact] public void NoUserDefinedConversionsThrow() { var source = @" class C { static void Main() { throw new Convertible(); } } class Convertible { public static implicit operator System.Exception(Convertible c) { throw null; } }"; CreateCompilation(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (6,15): error CS0155: The type caught or thrown must be derived from System.Exception Diagnostic(ErrorCode.ERR_BadExceptionType, "new Convertible()")); CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void NoUserDefinedConversionsCatch1() { var source = @" class C { static void Main() { try { } catch(Convertible) { } } } class Convertible { public static implicit operator System.Exception(Convertible c) { throw null; } }"; CreateCompilation(source).VerifyDiagnostics( // (9,15): error CS0155: The type caught or thrown must be derived from System.Exception Diagnostic(ErrorCode.ERR_BadExceptionType, "Convertible")); } [Fact] public void NoUserDefinedConversionsCatch2() { var source = @" class C { static void Main() { try { } catch (Exception1) { } catch (Exception2) { } } } class Exception1 : System.Exception { } class Exception2 : System.Exception { public static implicit operator Exception1(Exception2 e) { throw null; } }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void NoUserDefinedConversionsCaseLabel1() { var source = @" class C { static void Main() { switch (0) { case default(Convertible): return; } } } class Convertible { public static implicit operator int(Convertible e) { return 0; } }"; CreateCompilation(source).VerifyDiagnostics( // (8,18): error CS0150: A constant value is expected // case default(Convertible): return; Diagnostic(ErrorCode.ERR_ConstantExpected, "default(Convertible)").WithLocation(8, 18) ); } [Fact] public void NoUserDefinedConversionsCaseLabel2() { var source = @" class C { static void Main() { const Convertible c = null; switch (0) { case c: return; } } } class Convertible { public static implicit operator int(Convertible e) { return 0; } }"; CreateCompilation(source).VerifyDiagnostics( // (9,18): error CS0150: A constant value is expected // case c: return; Diagnostic(ErrorCode.ERR_ConstantExpected, "c").WithLocation(9, 18) ); } [Fact] public void NoUserDefinedConversionsUsing() { var il = @" .class public sequential ansi sealed beforefieldinit ConvertibleToIDisposable extends [mscorlib]System.ValueType { .method public hidebysig specialname static class [mscorlib]System.IDisposable op_Implicit(valuetype ConvertibleToIDisposable e) cil managed { ldnull ret } } "; var csharp = @" class C { static void Main() { using (var d = new ConvertibleToIDisposable()) { } } }"; CreateCompilationWithILAndMscorlib40(csharp, il).VerifyDiagnostics( // (6,16): error CS1674: 'ConvertibleToIDisposable': type used in a using statement must be implicitly convertible to 'System.IDisposable'. Diagnostic(ErrorCode.ERR_NoConvToIDisp, "var d = new ConvertibleToIDisposable()").WithArguments("ConvertibleToIDisposable")); } [WorkItem(11221, "DevDiv_Projects/Roslyn")] [Fact] public void OverflowInImplicitConversion() { var source = @"class C { public static explicit operator C(byte x) { return null; } static void Main() { var b = (C)1000M; } }"; CreateCompilation(source).VerifyDiagnostics( // (10,17): error CS0031: Constant value '1000M' cannot be converted to a 'byte' // var b = (C)1000M; Diagnostic(ErrorCode.ERR_ConstOutOfRange, "1000M").WithArguments("1000M", "byte") ); } [WorkItem(529568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529568")] [Fact()] public void AmbiguousConversions() { var source = @" // Tests conversions of generic constructed types - both open and closed. using System; public class A { } public class B { } public class C { } public class G0 { public override string ToString() { return ""G0""; } } public class G1<R> : G0 { public override string ToString() { return string.Format(""G1<{0}>"", typeof(R)); } } public class GS2<R, S> : G1<S> { public override string ToString() { return string.Format(""GS2<{0},{1}>"", typeof(R), typeof(S)); } } public class GS3<R, S, T> : GS2<S, T> { public override string ToString() { return string.Format(""GS3<{0},{1},{2}>"", typeof(R), typeof(S), typeof(T)); } } // Parallel hierarchy. public class H0 { public override string ToString() { return ""H0""; } public static implicit operator G0(H0 h) { Console.Write(""[H0->G0] ""); return new G0(); } } public class H1<R> : H0 { public override string ToString() { return string.Format(""H1<{0}>"", typeof(R)); } public static implicit operator G1<R>(H1<R> h) { Console.Write(""[H1->G1] ""); return new G1<R>(); } } public class HS2<R, S> : H1<S> { public override string ToString() { return string.Format(""HS2<{0},{1}>"", typeof(R), typeof(S)); } public static implicit operator GS2<R,S>(HS2<R,S> h) { Console.Write(""[HS2->GS2] ""); return new GS2<R,S>(); } } public class HS3<R, S, T> : HS2<S, T> { public override string ToString() { return string.Format(""HS3<{0},{1},{2}>"", typeof(R), typeof(S), typeof(T)); } public static implicit operator GS3<R,S,T>(HS3<R,S,T> h) { Console.Write(""[HS3->GS3] ""); return new GS3<R,S,T>(); } } // Complex constructed base types. public class GC2<R, S> : G1<G1<S>> { public override string ToString() { return string.Format(""GC2<{0},{1}>"", typeof(R), typeof(S)); } } public class GC3<R, S, T> : GC2<G1<T>, GC2<R, G1<S>>> { public override string ToString() { return string.Format(""GC3<{0},{1},{2}>"", typeof(R), typeof(S), typeof(T)); } } // Parallel hierarchy. public class HC2<R, S> : H1<G1<S>> { public override string ToString() { return string.Format(""HC2<{0},{1}>"", typeof(R), typeof(S)); } public static implicit operator GC2<R,S>(HC2<R,S> h) { Console.Write(""[HC2->GC2] ""); return new GC2<R,S>(); } } public class HC3<R, S, T> : HC2<G1<T>, GC2<R, G1<S>>> { public override string ToString() { return string.Format(""HC3<{0},{1},{2}>"", typeof(R), typeof(S), typeof(T)); } public static implicit operator GC3<R,S,T>(HC3<R,S,T> h) { Console.Write(""[HC3->GC3] ""); return new GC3<R,S,T>(); } } public class HH2<R, S> : H1<H1<S>> { public override string ToString() { return string.Format(""HH2<{0},{1}>"", typeof(R), typeof(S)); } public static implicit operator GC2<R,S>(HH2<R,S> h) { Console.Write(""[HH2->GC2] ""); return new GC2<R,S>(); } } public class HH3<R, S, T> : HH2<H1<T>, HH2<R, H1<S>>> { public override string ToString() { return string.Format(""HH3<{0},{1},{2}>"", typeof(R), typeof(S), typeof(T)); } public static implicit operator GC3<R,S,T>(HH3<R,S,T> h) { Console.Write(""[HH3->GC3] ""); return new GC3<R,S,T>(); } } public class Test { public static void F0(G0 g) { Console.WriteLine(""F0({0})"", g); } public static void F1<R>(G1<R> g) { Console.WriteLine(""F1<{0}>({1})"", typeof(R), g); } public static void FS2<R,S>(GS2<R, S> g) { Console.WriteLine(""FS2<{0},{1}>({2})"", typeof(R), typeof(S), g); } public static void FS3<R,S,T>(GS3<R, S, T> g) { Console.WriteLine(""FS3<{0},{1},{2}>({3})"", typeof(R), typeof(S), typeof(T), g); } public static void FC2<R,S>(GC2<R, S> g) { Console.WriteLine(""FC2<{0},{1}>({2})"", typeof(R), typeof(S), g); } public static void FC3<R,S,T>(GC3<R, S, T> g) { Console.WriteLine(""FC3<{0},{1},{2}>({3})"", typeof(R), typeof(S), typeof(T), g); } public static void Main() { Console.WriteLine(""***** Start generic constructed type conversion test""); G0 g0 = new G0(); G1<A> g1a = new G1<A>(); GS2<A, B> gs2ab = new GS2<A, B>(); GS3<A, B, C> gs3abc = new GS3<A, B, C>(); H0 h0 = new H0(); H1<A> h1a = new H1<A>(); HS2<A, B> hs2ab = new HS2<A, B>(); HS3<A, B, C> hs3abc = new HS3<A, B, C>(); GC2<A, B> gc2ab = new GC2<A, B>(); GC3<A, B, C> gc3abc = new GC3<A, B, C>(); HC2<A, B> hc2ab = new HC2<A, B>(); HC3<A, B, C> hc3abc = new HC3<A, B, C>(); HH2<A, B> hh2ab = new HH2<A, B>(); HH3<A, B, C> hh3abc = new HH3<A, B, C>(); // ***** Implicit user defined conversion. // H1<A> -> G0: ambiguous F0(h1a); // HS2<A,B> -> G0: ambiguous F0(hs2ab); // HS3<A,B,C> -> G0: ambiguous F0(hs3abc); // H1<A> -> G1<A> F1(h1a); // HS2<A,B> -> G1<B>: ambiguous F1<B>(hs2ab); // HS3<A,B,C> -> G1<C>: ambiguous F1<C>(hs3abc); // HS2<A,B> -> GS2<A,B> FS2(hs2ab); // HS3<A,B,C> -> GS2<B,C>: ambiguous FS2<B,C>(hs3abc); // HS3<A,B,C> -> GS3<A,B,C> FS3(hs3abc); // * Complex // HC2<A,B> -> G0: ambiguous F0(hc2ab); // HC3<A,B,C> -> G0: ambiguous F0(hc3abc); // HC2<A,B> -> G1<G1<B>>: ambiguous F1<G1<B>>(hc2ab); // HC3<A,B,C> -> G1<G1<GC2<A,G1<B>>>>: ambiguous F1<G1<GC2<A,G1<B>>>>(hc3abc); // HC2<A,B> -> GC2<A,B> FC2(hc2ab); // HC3<A,B,C> -> GC2<G1<C>,GC2<A,G1<B>>>: ambiguous FC2<G1<C>,GC2<A,G1<B>>>(hc3abc); // HC3<A,B,C> -> GC3<A,B,C> FC3(hc3abc); // HH2<A,B> -> G0: ambiguous F0(hh2ab); // HH3<A,B,C> -> G0: ambiguous F0(hh3abc); // HH2<A,B> -> G1<*> F1(hh2ab); // HH3<A,B,C> -> G1<*> F1(hh3abc); // HH3<A,B,C> -> G1<*> F1(hh3abc); // HH2<A,B> -> GC2<A,B> FC2(hh2ab); // HH3<A,B,C> -> GC2<*> FC2(hh3abc); // HH3<A,B,C> -> GC2<*> FC2(hh3abc); // HG3<A,B,C> -> GC3<A,B,C> FC3(hh3abc); Console.WriteLine(""***** End generic constructed type conversion test""); } } "; CreateCompilation(source).VerifyDiagnostics( // (126,12): error CS0457: Ambiguous user defined conversions 'H1<A>.implicit operator G1<A>(H1<A>)' and 'H0.implicit operator G0(H0)' when converting from 'H1<A>' to 'G0' // F0(h1a); Diagnostic(ErrorCode.ERR_AmbigUDConv, "h1a").WithArguments("H1<A>.implicit operator G1<A>(H1<A>)", "H0.implicit operator G0(H0)", "H1<A>", "G0"), // (129,12): error CS0457: Ambiguous user defined conversions 'HS2<A, B>.implicit operator GS2<A, B>(HS2<A, B>)' and 'H1<B>.implicit operator G1<B>(H1<B>)' when converting from 'HS2<A, B>' to 'G0' // F0(hs2ab); Diagnostic(ErrorCode.ERR_AmbigUDConv, "hs2ab").WithArguments("HS2<A, B>.implicit operator GS2<A, B>(HS2<A, B>)", "H1<B>.implicit operator G1<B>(H1<B>)", "HS2<A, B>", "G0"), // (132,12): error CS0457: Ambiguous user defined conversions 'HS3<A, B, C>.implicit operator GS3<A, B, C>(HS3<A, B, C>)' and 'HS2<B, C>.implicit operator GS2<B, C>(HS2<B, C>)' when converting from 'HS3<A, B, C>' to 'G0' // F0(hs3abc); Diagnostic(ErrorCode.ERR_AmbigUDConv, "hs3abc").WithArguments("HS3<A, B, C>.implicit operator GS3<A, B, C>(HS3<A, B, C>)", "HS2<B, C>.implicit operator GS2<B, C>(HS2<B, C>)", "HS3<A, B, C>", "G0"), // (135,9): error CS0411: The type arguments for method 'Test.F1<R>(G1<R>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F1(h1a); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F1").WithArguments("Test.F1<R>(G1<R>)"), // (138,15): error CS0457: Ambiguous user defined conversions 'HS2<A, B>.implicit operator GS2<A, B>(HS2<A, B>)' and 'H1<B>.implicit operator G1<B>(H1<B>)' when converting from 'HS2<A, B>' to 'G1<B>' // F1<B>(hs2ab); Diagnostic(ErrorCode.ERR_AmbigUDConv, "hs2ab").WithArguments("HS2<A, B>.implicit operator GS2<A, B>(HS2<A, B>)", "H1<B>.implicit operator G1<B>(H1<B>)", "HS2<A, B>", "G1<B>"), // (141,15): error CS0457: Ambiguous user defined conversions 'HS3<A, B, C>.implicit operator GS3<A, B, C>(HS3<A, B, C>)' and 'HS2<B, C>.implicit operator GS2<B, C>(HS2<B, C>)' when converting from 'HS3<A, B, C>' to 'G1<C>' // F1<C>(hs3abc); Diagnostic(ErrorCode.ERR_AmbigUDConv, "hs3abc").WithArguments("HS3<A, B, C>.implicit operator GS3<A, B, C>(HS3<A, B, C>)", "HS2<B, C>.implicit operator GS2<B, C>(HS2<B, C>)", "HS3<A, B, C>", "G1<C>"), // (144,9): error CS0411: The type arguments for method 'Test.FS2<R, S>(GS2<R, S>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // FS2(hs2ab); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "FS2").WithArguments("Test.FS2<R, S>(GS2<R, S>)"), // (147,18): error CS0457: Ambiguous user defined conversions 'HS3<A, B, C>.implicit operator GS3<A, B, C>(HS3<A, B, C>)' and 'HS2<B, C>.implicit operator GS2<B, C>(HS2<B, C>)' when converting from 'HS3<A, B, C>' to 'GS2<B, C>' // FS2<B,C>(hs3abc); Diagnostic(ErrorCode.ERR_AmbigUDConv, "hs3abc").WithArguments("HS3<A, B, C>.implicit operator GS3<A, B, C>(HS3<A, B, C>)", "HS2<B, C>.implicit operator GS2<B, C>(HS2<B, C>)", "HS3<A, B, C>", "GS2<B, C>"), // (150,9): error CS0411: The type arguments for method 'Test.FS3<R, S, T>(GS3<R, S, T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // FS3(hs3abc); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "FS3").WithArguments("Test.FS3<R, S, T>(GS3<R, S, T>)"), // (155,12): error CS0457: Ambiguous user defined conversions 'HC2<A, B>.implicit operator GC2<A, B>(HC2<A, B>)' and 'H1<G1<B>>.implicit operator G1<G1<B>>(H1<G1<B>>)' when converting from 'HC2<A, B>' to 'G0' // F0(hc2ab); Diagnostic(ErrorCode.ERR_AmbigUDConv, "hc2ab").WithArguments("HC2<A, B>.implicit operator GC2<A, B>(HC2<A, B>)", "H1<G1<B>>.implicit operator G1<G1<B>>(H1<G1<B>>)", "HC2<A, B>", "G0"), // (158,12): error CS0457: Ambiguous user defined conversions 'HC3<A, B, C>.implicit operator GC3<A, B, C>(HC3<A, B, C>)' and 'HC2<G1<C>, GC2<A, G1<B>>>.implicit operator GC2<G1<C>, GC2<A, G1<B>>>(HC2<G1<C>, GC2<A, G1<B>>>)' when converting from 'HC3<A, B, C>' to 'G0' // F0(hc3abc); Diagnostic(ErrorCode.ERR_AmbigUDConv, "hc3abc").WithArguments("HC3<A, B, C>.implicit operator GC3<A, B, C>(HC3<A, B, C>)", "HC2<G1<C>, GC2<A, G1<B>>>.implicit operator GC2<G1<C>, GC2<A, G1<B>>>(HC2<G1<C>, GC2<A, G1<B>>>)", "HC3<A, B, C>", "G0"), // (161,19): error CS0457: Ambiguous user defined conversions 'HC2<A, B>.implicit operator GC2<A, B>(HC2<A, B>)' and 'H1<G1<B>>.implicit operator G1<G1<B>>(H1<G1<B>>)' when converting from 'HC2<A, B>' to 'G1<G1<B>>' // F1<G1<B>>(hc2ab); Diagnostic(ErrorCode.ERR_AmbigUDConv, "hc2ab").WithArguments("HC2<A, B>.implicit operator GC2<A, B>(HC2<A, B>)", "H1<G1<B>>.implicit operator G1<G1<B>>(H1<G1<B>>)", "HC2<A, B>", "G1<G1<B>>"), // (164,30): error CS0457: Ambiguous user defined conversions 'HC3<A, B, C>.implicit operator GC3<A, B, C>(HC3<A, B, C>)' and 'HC2<G1<C>, GC2<A, G1<B>>>.implicit operator GC2<G1<C>, GC2<A, G1<B>>>(HC2<G1<C>, GC2<A, G1<B>>>)' when converting from 'HC3<A, B, C>' to 'G1<G1<GC2<A, G1<B>>>>' // F1<G1<GC2<A,G1<B>>>>(hc3abc); Diagnostic(ErrorCode.ERR_AmbigUDConv, "hc3abc").WithArguments("HC3<A, B, C>.implicit operator GC3<A, B, C>(HC3<A, B, C>)", "HC2<G1<C>, GC2<A, G1<B>>>.implicit operator GC2<G1<C>, GC2<A, G1<B>>>(HC2<G1<C>, GC2<A, G1<B>>>)", "HC3<A, B, C>", "G1<G1<GC2<A, G1<B>>>>"), // (167,9): error CS0411: The type arguments for method 'Test.FC2<R, S>(GC2<R, S>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // FC2(hc2ab); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "FC2").WithArguments("Test.FC2<R, S>(GC2<R, S>)"), // (170,33): error CS0457: Ambiguous user defined conversions 'HC3<A, B, C>.implicit operator GC3<A, B, C>(HC3<A, B, C>)' and 'HC2<G1<C>, GC2<A, G1<B>>>.implicit operator GC2<G1<C>, GC2<A, G1<B>>>(HC2<G1<C>, GC2<A, G1<B>>>)' when converting from 'HC3<A, B, C>' to 'GC2<G1<C>, GC2<A, G1<B>>>' // FC2<G1<C>,GC2<A,G1<B>>>(hc3abc); Diagnostic(ErrorCode.ERR_AmbigUDConv, "hc3abc").WithArguments("HC3<A, B, C>.implicit operator GC3<A, B, C>(HC3<A, B, C>)", "HC2<G1<C>, GC2<A, G1<B>>>.implicit operator GC2<G1<C>, GC2<A, G1<B>>>(HC2<G1<C>, GC2<A, G1<B>>>)", "HC3<A, B, C>", "GC2<G1<C>, GC2<A, G1<B>>>"), // (173,9): error CS0411: The type arguments for method 'Test.FC3<R, S, T>(GC3<R, S, T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // FC3(hc3abc); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "FC3").WithArguments("Test.FC3<R, S, T>(GC3<R, S, T>)"), // (178,12): error CS0457: Ambiguous user defined conversions 'HH2<A, B>.implicit operator GC2<A, B>(HH2<A, B>)' and 'H1<H1<B>>.implicit operator G1<H1<B>>(H1<H1<B>>)' when converting from 'HH2<A, B>' to 'G0' // F0(hh2ab); Diagnostic(ErrorCode.ERR_AmbigUDConv, "hh2ab").WithArguments("HH2<A, B>.implicit operator GC2<A, B>(HH2<A, B>)", "H1<H1<B>>.implicit operator G1<H1<B>>(H1<H1<B>>)", "HH2<A, B>", "G0"), // (181,12): error CS0457: Ambiguous user defined conversions 'HH3<A, B, C>.implicit operator GC3<A, B, C>(HH3<A, B, C>)' and 'HH2<H1<C>, HH2<A, H1<B>>>.implicit operator GC2<H1<C>, HH2<A, H1<B>>>(HH2<H1<C>, HH2<A, H1<B>>>)' when converting from 'HH3<A, B, C>' to 'G0' // F0(hh3abc); Diagnostic(ErrorCode.ERR_AmbigUDConv, "hh3abc").WithArguments("HH3<A, B, C>.implicit operator GC3<A, B, C>(HH3<A, B, C>)", "HH2<H1<C>, HH2<A, H1<B>>>.implicit operator GC2<H1<C>, HH2<A, H1<B>>>(HH2<H1<C>, HH2<A, H1<B>>>)", "HH3<A, B, C>", "G0"), // (184,9): error CS0411: The type arguments for method 'Test.F1<R>(G1<R>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F1(hh2ab); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F1").WithArguments("Test.F1<R>(G1<R>)"), // (187,9): error CS0411: The type arguments for method 'Test.F1<R>(G1<R>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F1(hh3abc); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F1").WithArguments("Test.F1<R>(G1<R>)"), // (190,9): error CS0411: The type arguments for method 'Test.F1<R>(G1<R>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F1(hh3abc); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F1").WithArguments("Test.F1<R>(G1<R>)"), // (193,9): error CS0411: The type arguments for method 'Test.FC2<R, S>(GC2<R, S>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // FC2(hh2ab); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "FC2").WithArguments("Test.FC2<R, S>(GC2<R, S>)"), // (196,9): error CS0411: The type arguments for method 'Test.FC2<R, S>(GC2<R, S>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // FC2(hh3abc); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "FC2").WithArguments("Test.FC2<R, S>(GC2<R, S>)"), // (199,9): error CS0411: The type arguments for method 'Test.FC2<R, S>(GC2<R, S>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // FC2(hh3abc); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "FC2").WithArguments("Test.FC2<R, S>(GC2<R, S>)"), // (202,9): error CS0411: The type arguments for method 'Test.FC3<R, S, T>(GC3<R, S, T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // FC3(hh3abc); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "FC3").WithArguments("Test.FC3<R, S, T>(GC3<R, S, T>)") //Dev10 //error CS0457: Ambiguous user defined conversions 'H1<A>.implicit operator G1<A>(H1<A>)' and 'H0.implicit operator G0(H0)' when converting from 'H1<A>' to 'G0' //error CS0457: Ambiguous user defined conversions 'HS2<A,B>.implicit operator GS2<A,B>(HS2<A,B>)' and 'H0.implicit operator G0(H0)' when converting from 'HS2<A,B>' to 'G0' //error CS0457: Ambiguous user defined conversions 'HS3<A,B,C>.implicit operator GS3<A,B,C>(HS3<A,B,C>)' and 'H0.implicit operator G0(H0)' when converting from 'HS3<A,B,C>' to 'G0' //error CS0411: The type arguments for method 'Test.F1<R>(G1<R>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. //error CS0457: Ambiguous user defined conversions 'HS2<A,B>.implicit operator GS2<A,B>(HS2<A,B>)' and 'H1<B>.implicit operator G1<B>(H1<B>)' when converting from 'HS2<A,B>' to 'G1<B>' //error CS0457: Ambiguous user defined conversions 'HS3<A,B,C>.implicit operator GS3<A,B,C>(HS3<A,B,C>)' and 'H1<C>.implicit operator G1<C>(H1<C>)' when converting from 'HS3<A,B,C>' to 'G1<C>' //error CS0411: The type arguments for method 'Test.FS2<R,S>(GS2<R,S>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. //error CS0457: Ambiguous user defined conversions 'HS3<A,B,C>.implicit operator GS3<A,B,C>(HS3<A,B,C>)' and 'HS2<B,C>.implicit operator GS2<B,C>(HS2<B,C>)' when converting from 'HS3<A,B,C>' to 'GS2<B,C>' //error CS0411: The type arguments for method 'Test.FS3<R,S,T>(GS3<R,S,T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. //error CS0457: Ambiguous user defined conversions 'HC2<A,B>.implicit operator GC2<A,B>(HC2<A,B>)' and 'H0.implicit operator G0(H0)' when converting from 'HC2<A,B>' to 'G0' //error CS0457: Ambiguous user defined conversions 'HC3<A,B,C>.implicit operator GC3<A,B,C>(HC3<A,B,C>)' and 'H0.implicit operator G0(H0)' when converting from 'HC3<A,B,C>' to 'G0' //error CS0457: Ambiguous user defined conversions 'HC2<A,B>.implicit operator GC2<A,B>(HC2<A,B>)' and 'H1<G1<B>>.implicit operator G1<G1<B>>(H1<G1<B>>)' when converting from 'HC2<A,B>' to 'G1<G1<B>>' //error CS0457: Ambiguous user defined conversions 'HC3<A,B,C>.implicit operator GC3<A,B,C>(HC3<A,B,C>)' and 'H1<G1<GC2<A,G1<B>>>>.implicit operator G1<G1<GC2<A,G1<B>>>>(H1<G1<GC2<A,G1<B>>>>)' when converting from 'HC3<A,B,C>' to 'G1<G1<GC2<A,G1<B>>>>' //error CS0411: The type arguments for method 'Test.FC2<R,S>(GC2<R,S>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. //error CS0457: Ambiguous user defined conversions 'HC3<A,B,C>.implicit operator GC3<A,B,C>(HC3<A,B,C>)' and 'HC2<G1<C>,GC2<A,G1<B>>>.implicit operator GC2<G1<C>,GC2<A,G1<B>>>(HC2<G1<C>,GC2<A,G1<B>>>)' when converting from 'HC3<A,B,C>' to 'GC2<G1<C>,GC2<A,G1<B>>>' //error CS0411: The type arguments for method 'Test.FC3<R,S,T>(GC3<R,S,T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. //error CS0457: Ambiguous user defined conversions 'HH2<A,B>.implicit operator GC2<A,B>(HH2<A,B>)' and 'H0.implicit operator G0(H0)' when converting from 'HH2<A,B>' to 'G0' //error CS0457: Ambiguous user defined conversions 'HH3<A,B,C>.implicit operator GC3<A,B,C>(HH3<A,B,C>)' and 'H0.implicit operator G0(H0)' when converting from 'HH3<A,B,C>' to 'G0' //error CS0411: The type arguments for method 'Test.F1<R>(G1<R>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. //error CS0411: The type arguments for method 'Test.F1<R>(G1<R>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. //error CS0411: The type arguments for method 'Test.F1<R>(G1<R>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. //error CS0411: The type arguments for method 'Test.FC2<R,S>(GC2<R,S>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. //error CS0411: The type arguments for method 'Test.FC2<R,S>(GC2<R,S>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. //error CS0411: The type arguments for method 'Test.FC2<R,S>(GC2<R,S>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. //error CS0411: The type arguments for method 'Test.FC3<R,S,T>(GC3<R,S,T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. ); } [WorkItem(545361, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545361")] [ClrOnlyFact] public void NullableIntToStructViaDecimal() { var source = @" using System; public struct S { public static implicit operator S?(decimal d) { Console.Write(d); return new S(); } static void Test(bool b) { Console.Write(b ? 't' : 'f'); } static void Main() { int? i; S? s; i = 1; // Native compiler allows this, even though this is illegal by the spec. // there must be a standard implicit conversion either from int? to decimal // or from decimal to int? -- but neither of those conversions are implicit. // The native compiler instead checks to see if there is a standard conversion // between int and decimal, which there is. // Roslyn also allows this. // Note that there is a codegen difference between the native compiler and Roslyn // here, though the difference actually makes no difference other than the // Roslyn codegen being less efficient. The Roslyn compiler generates this as: // // start with int? // lifted conversion to decimal? (cannot fail) // explicit conversion to decimal (can fail) // user-defined conversion to S? // explicit conversion to S. // // The native compiler generates this as // // start with int? // explicit conversion to int (can fail) // implicit conversion to decimal // user-defined conversion to S? // explicit conversion to S. // // The native code is better; there's no reason to do the lifted conversion // from int? to decimal? and then just check to see if the decimal? is null; // we could simply check if the int? is null in the first place. // // There are many places where Roslyn's nullable codegen is inefficient and // this is one of them. We will likely fix this in a later milestone. s = (S)i; Test(s != null); // true // Let's try the same thing, but with a null. Whether we use the Roslyn or the // native codegen, we should get an exception. bool threw = false; try { i = null; s = (S)i; } catch { threw = true; } Test(threw); // true // Now we come to an interesting case. // // First off, this should not even be legal, this time for two reasons. First, // because again, there is no explicit standard conversion from int? to decimal. // Second, the native compiler binds this as a lifted conversion, even though // a lifted conversion requires that both the input and output types of the // operator be non-nullable value types; obviously the output type is not a non-nullable // value type. // // Even worse, the native compiler allows this and then generates bad code. It generates // a null check on i, but then forgets to generate a conversion from i.Value to decimal // before doing the call. // // Roslyn matches the native compiler's analysis; it treats this as a lifted conversion // even though it ought not to. Roslyn however gets the codegen correct. // i = null; s = (S?)i; Test(s == null); // Roslyn: true. Native compiler: generates bad code that crashes the CLR. } } "; CompileAndVerify(source, expectedOutput: @"1ttt"); } [ConditionalFact(typeof(ClrOnly), typeof(DesktopOnly))] [WorkItem(545471, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545471")] [WorkItem(18446, "https://github.com/dotnet/roslyn/issues/18446")] public void CheckedConversionsInExpressionTrees() { var source = @" using System; using System.Linq.Expressions; namespace ExpressionTest { public struct MyStruct { public static MyStruct operator +(MyStruct c1, MyStruct c2) { return c1; } public static explicit operator int(MyStruct m) { return 0; } public static void Main() { Expression<Func<MyStruct, MyStruct?, MyStruct?>> eb1 = (c1, c2) => c1 + c2; Expression<Func<MyStruct, MyStruct?, MyStruct?>> eb2 = (c1, c2) => checked(c1 + c2); Expression<Func<MyStruct, MyStruct?, MyStruct?>> eb3 = (c1, c2) => unchecked(c1 + c2); Expression<Func<int?, int, int?>> ee1 = (c1, c2) => c1 + c2; Expression<Func<int?, int, int?>> ee2 = (c1, c2) => checked(c1 + c2); Expression<Func<int?, int, int?>> ee3 = (c1, c2) => unchecked(c1 + c2); object[] tests = new object[] { eb1, eb2, eb3, ee1, ee2, ee3, }; foreach (object test in tests) { Console.WriteLine(test); } } } } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.ReleaseExe); CompileAndVerify(compilation, expectedOutput: @" (c1, c2) => (Convert(c1) + c2) (c1, c2) => (Convert(c1) + c2) (c1, c2) => (Convert(c1) + c2) (c1, c2) => (c1 + Convert(c2)) (c1, c2) => (c1 + Convert(c2)) (c1, c2) => (c1 + Convert(c2)) "); } [WorkItem(647055, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/647055")] [Fact] public void AmbiguousImplicitExplicitUserDefined() { var source = @" class Program { void Test(int[] a) { C<int> x1 = (C<int>)1; // Expression to type foreach (C<int> x2 in a) { } // Type to type } } class C<T> { public static implicit operator C<T>(T x) { return null; } public static explicit operator C<T>(int x) { return null; } } "; var comp = (Compilation)CreateCompilation(source); comp.VerifyDiagnostics( // (6,21): error CS0457: Ambiguous user defined conversions 'C<int>.explicit operator C<int>(int)' and 'C<int>.implicit operator C<int>(int)' when converting from 'int' to 'C<int>' // C<int> x1 = (C<int>)1; // Expression to type Diagnostic(ErrorCode.ERR_AmbigUDConv, "(C<int>)1").WithArguments("C<int>.explicit operator C<int>(int)", "C<int>.implicit operator C<int>(int)", "int", "C<int>"), // (8,9): error CS0457: Ambiguous user defined conversions 'C<int>.explicit operator C<int>(int)' and 'C<int>.implicit operator C<int>(int)' when converting from 'int' to 'C<int>' // foreach (C<int> x2 in a) { } // Type to type Diagnostic(ErrorCode.ERR_AmbigUDConv, "foreach").WithArguments("C<int>.explicit operator C<int>(int)", "C<int>.implicit operator C<int>(int)", "int", "C<int>")); var destinationType = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("C").Construct(comp.GetSpecialType(SpecialType.System_Int32)); var conversionSymbols = destinationType.GetMembers().OfType<IMethodSymbol>().Where(m => m.MethodKind == MethodKind.Conversion); Assert.Equal(2, conversionSymbols.Count()); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var castSyntax = tree.GetRoot().DescendantNodes().OfType<CastExpressionSyntax>().Single(); var castInfo = model.GetSymbolInfo(castSyntax); Assert.Null(castInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, castInfo.CandidateReason); AssertEx.SetEqual(castInfo.CandidateSymbols, conversionSymbols); var forEachSyntax = tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single(); var memberModel = ((CSharpSemanticModel)model).GetMemberModel(forEachSyntax); var boundForEach = memberModel.GetBoundNodes(forEachSyntax).OfType<BoundForEachStatement>().Single(); var elementConversion = boundForEach.ElementConversion; Assert.Equal(LookupResultKind.OverloadResolutionFailure, elementConversion.ResultKind); AssertEx.SetEqual(elementConversion.OriginalUserDefinedConversions.GetPublicSymbols(), conversionSymbols); } [WorkItem(715207, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/715207")] [ClrOnlyFact] public void LiftingReturnTypeOfExplicitUserDefinedConversion() { var source = @" class C { char? Test(object o) { return (char?)(BigInteger)o; } } struct BigInteger { public static explicit operator ushort(BigInteger b) { return 0; } }"; CompileAndVerify(source).VerifyIL("C.Test", @" { // Code size 17 (0x11) .maxstack 1 IL_0000: ldarg.1 IL_0001: unbox.any ""BigInteger"" IL_0006: call ""ushort BigInteger.op_Explicit(BigInteger)"" IL_000b: newobj ""char?..ctor(char)"" IL_0010: ret } "); } [WorkItem(737732, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/737732")] [Fact] public void ConsiderSourceExpressionWhenDeterminingBestUserDefinedConversion() { var source = @" public class C { public static explicit operator C(double d) { return null; } public static explicit operator C(byte b) { return null; } } public class Test { C M() { return (C)0; } } "; var comp = (Compilation)CreateCompilation(source); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var syntax = tree.GetRoot().DescendantNodes().OfType<CastExpressionSyntax>().Single(); var symbol = model.GetSymbolInfo(syntax).Symbol; Assert.Equal(SymbolKind.Method, symbol.Kind); var method = (IMethodSymbol)symbol; Assert.Equal(MethodKind.Conversion, method.MethodKind); Assert.Equal(comp.GlobalNamespace.GetMember<INamedTypeSymbol>("C"), method.ContainingType); Assert.Equal(SpecialType.System_Byte, method.Parameters.Single().Type.SpecialType); } [WorkItem(737732, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/737732")] [Fact] public void Repro737732() { var source = @" using System; public struct C { public static explicit operator C(decimal d) { return default(C); } public static explicit operator C(double d) { return default(C); } public static implicit operator C(byte d) { return default(C); } C Test() { return (C)0; } } "; var comp = (Compilation)CreateCompilation(source); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var syntax = tree.GetRoot().DescendantNodes().OfType<CastExpressionSyntax>().Single(); var symbol = model.GetSymbolInfo(syntax).Symbol; Assert.Equal(SymbolKind.Method, symbol.Kind); var method = (IMethodSymbol)symbol; Assert.Equal(MethodKind.Conversion, method.MethodKind); Assert.Equal(comp.GlobalNamespace.GetMember<INamedTypeSymbol>("C"), method.ContainingType); Assert.Equal(SpecialType.System_Byte, method.Parameters.Single().Type.SpecialType); } [WorkItem(742345, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/742345")] [ClrOnlyFact] public void MethodGroupConversion_ContravarianceAndDynamic() { var source = @" delegate void In<in T>(T t); public class C { static void Main() { M(F); } static void F(string s) { } static void M(In<dynamic> f) { System.Console.WriteLine('A'); } // Better, if both are applicable. static void M(In<string> f) { System.Console.WriteLine('B'); } // Actually chosen, since the other isn't applicable. } "; CompileAndVerify(source, expectedOutput: "B"); } [WorkItem(742345, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/742345")] [Fact] public void MethodGroupConversion_CovarianceAndDynamic() { var source = @" delegate T Out<out T>(); public class C { static void Main() { M(F); } static dynamic F() { throw null; } static void M(Out<string> f) { } // Better, if both are applicable. static void M(Out<dynamic> f) { } } "; // The return type of F isn't considered until the delegate compatibility check, // which happens AFTER determining that the method group conversion exists. As // a result, both methods are considered applicable and the "wrong" one is chosen. CreateCompilationWithMscorlib40AndSystemCore(source, parseOptions: TestOptions.WithoutImprovedOverloadCandidates).VerifyDiagnostics( // (8,11): error CS0407: 'dynamic C.F()' has the wrong return type // M(F); Diagnostic(ErrorCode.ERR_BadRetType, "F").WithArguments("C.F()", "dynamic")); // However, we later added a feature that takes the return type into account. CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics(); } [WorkItem(737971, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/737971")] [Fact] public void ConversionsFromExpressions() { var source = @" using System; public enum E { A } public class Q { public static implicit operator Q(Func<int> f) { return null; } } public class R { public static implicit operator R(E e) { return null; } } public class S { public static implicit operator S(byte b) { return null; } } public struct T { public static implicit operator T(string s) { return default(T); } } public struct U { public unsafe static implicit operator U(void* p) { return default(U); } } public struct V { public static implicit operator V(dynamic[] d) { return default(V); } } public class Test { static void Main() { // Anonymous function { Q q; q = () => 1; //CS1660 q = (Q)(() => 1); } // Method group { Q q; q = F; //CS0428 q = (Q)F; } //Enum { R r; r = 0; //CS0029 r = (E)0; } // Numeric constant { S s; s = 0; s = (S)0; } // Null literal { T t; t = null; t = (T)null; } // Pointer unsafe { U u; u = null; u = &u; u = (U)null; u = (U)(&u); } } static int F() { return 0; } } "; // NOTE: It's pretty wacky that some of these implicit UDCs can only be applied via explicit (cast) conversions, // but that's the native behavior. We need to replicate it for back-compat, but most of the strangeness will // not be spec'd. CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (46,17): error CS1660: Cannot convert lambda expression to type 'Q' because it is not a delegate type // q = () => 1; //CS1660 Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "Q"), // (53,17): error CS0428: Cannot convert method group 'F' to non-delegate type 'Q'. Did you intend to invoke the method? // q = F; //CS0428 Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "Q"), // (60,17): error CS0029: Cannot implicitly convert type 'int' to 'R' // r = 0; //CS0029 Diagnostic(ErrorCode.ERR_NoImplicitConv, "0").WithArguments("int", "R")); } [Fact] public void BoxingConversionsForThisArgument() { var source = @"static class E { internal static void F(this object o) { System.Console.WriteLine(o); } } class C { static void Main() { 1.F(); 'c'.F(); ""s"".F(); (1, (2, 3)).F(); } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore( source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, expectedOutput: @"1 c s (1, (2, 3))"); } [Fact] public void SkipNumericConversionsForThisArgument() { var source = @"static class E { internal static void F(this long l) { } internal static void G(this (long, long) t) { } internal static void H(this (object, object) t) { } } class C { static void Main() { int i = 1; var t = (i, i); E.F(i); i.F(); E.G(t); t.G(); E.H(t); t.H(); } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }); comp.VerifyDiagnostics( // (14,9): error CS1929: 'int' does not contain a definition for 'F' and the best extension method overload 'E.F(long)' requires a receiver of type 'long' // i.F(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "i").WithArguments("int", "F", "E.F(long)", "long").WithLocation(14, 9), // (16,9): error CS1929: '(int, int)' does not contain a definition for 'G' and the best extension method overload 'E.G((long, long))' requires a receiver of type '(long, long)' // t.G(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "t").WithArguments("(int, int)", "G", "E.G((long, long))", "(long, long)").WithLocation(16, 9)); } [Fact] public void SkipNullableConversionsForThisArgument() { var source = @"static class E { internal static void F(this int? i) { } internal static void G(this (int, int)? t) { } } class C { static void Main() { int i = 1; var t = (i, i); E.F(i); i.F(); E.F((int?)i); ((int?)i).F(); E.G(t); t.G(); E.G(((int, int)?)t); (((int, int)?)t).G(); } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }); comp.VerifyDiagnostics( // (13,9): error CS1929: 'int' does not contain a definition for 'F' and the best extension method overload 'E.F(int?)' requires a receiver of type 'int?' // i.F(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "i").WithArguments("int", "F", "E.F(int?)", "int?").WithLocation(13, 9), // (17,9): error CS1929: '(int, int)' does not contain a definition for 'G' and the best extension method overload 'E.G((int, int)?)' requires a receiver of type '(int, int)?' // t.G(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "t").WithArguments("(int, int)", "G", "E.G((int, int)?)", "(int, int)?").WithLocation(17, 9)); } [Fact] public void SkipEnumerationConversionsForThisArgument() { var source = @"enum E { } static class C { static void F(this E e) { } static void G(this E? e) { } static void H(this (E, E?) t) { } static void Main() { const E e = default(E); F(e); e.F(); F(0); 0.F(); G(e); e.G(); G((E?)e); ((E?)e).G(); G(0); 0.G(); H((e, e)); (e, e).H(); H((e, (E?)e)); (e, (E?)e).H(); } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }); comp.VerifyDiagnostics( // (15,9): error CS1929: 'int' does not contain a definition for 'F' and the best extension method overload 'C.F(E)' requires a receiver of type 'E' // 0.F(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "0").WithArguments("int", "F", "C.F(E)", "E").WithLocation(15, 9), // (17,9): error CS1929: 'E' does not contain a definition for 'G' and the best extension method overload 'C.G(E?)' requires a receiver of type 'E?' // e.G(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "e").WithArguments("E", "G", "C.G(E?)", "E?").WithLocation(17, 9), // (21,9): error CS1929: 'int' does not contain a definition for 'G' and the best extension method overload 'C.G(E?)' requires a receiver of type 'E?' // 0.G(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "0").WithArguments("int", "G", "C.G(E?)", "E?").WithLocation(21, 9), // (23,9): error CS1929: '(E, E)' does not contain a definition for 'H' and the best extension method overload 'C.H((E, E?))' requires a receiver of type '(E, E?)' // (e, e).H(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "(e, e)").WithArguments("(E, E)", "H", "C.H((E, E?))", "(E, E?)").WithLocation(23, 9)); } [Fact] public void SkipConstantExpressionConversionsForThisArgument() { var source = @"static class C { static void S08(this sbyte arg) { } static void S16(this short arg) { } static void S32(this int arg) { } static void S64(this long arg) { } static void U08(this byte arg) { } static void U16(this ushort arg) { } static void U32(this uint arg) { } static void U64(this ulong arg) { } static void Main() { S08(1); S16(2); S32(3); S64(4); U08(5); U16(6); U32(7); U64(8); 1.S08(); 2.S16(); 3.S32(); 4.S64(); 5.U08(); 6.U16(); 7.U32(); 8.U64(); S64(9L); U64(10L); 9L.S64(); 10L.U64(); } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }); comp.VerifyDiagnostics( // (21,9): error CS1929: 'int' does not contain a definition for 'S08' and the best extension method overload 'C.S08(sbyte)' requires a receiver of type 'sbyte' // 1.S08(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "1").WithArguments("int", "S08", "C.S08(sbyte)", "sbyte").WithLocation(21, 9), // (22,9): error CS1929: 'int' does not contain a definition for 'S16' and the best extension method overload 'C.S16(short)' requires a receiver of type 'short' // 2.S16(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "2").WithArguments("int", "S16", "C.S16(short)", "short").WithLocation(22, 9), // (24,9): error CS1929: 'int' does not contain a definition for 'S64' and the best extension method overload 'C.S64(long)' requires a receiver of type 'long' // 4.S64(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "4").WithArguments("int", "S64", "C.S64(long)", "long").WithLocation(24, 9), // (25,9): error CS1929: 'int' does not contain a definition for 'U08' and the best extension method overload 'C.U08(byte)' requires a receiver of type 'byte' // 5.U08(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "5").WithArguments("int", "U08", "C.U08(byte)", "byte").WithLocation(25, 9), // (26,9): error CS1929: 'int' does not contain a definition for 'U16' and the best extension method overload 'C.U16(ushort)' requires a receiver of type 'ushort' // 6.U16(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "6").WithArguments("int", "U16", "C.U16(ushort)", "ushort").WithLocation(26, 9), // (27,9): error CS1929: 'int' does not contain a definition for 'U32' and the best extension method overload 'C.U32(uint)' requires a receiver of type 'uint' // 7.U32(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "7").WithArguments("int", "U32", "C.U32(uint)", "uint").WithLocation(27, 9), // (28,9): error CS1929: 'int' does not contain a definition for 'U64' and the best extension method overload 'C.U64(ulong)' requires a receiver of type 'ulong' // 8.U64(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "8").WithArguments("int", "U64", "C.U64(ulong)", "ulong").WithLocation(28, 9), // (32,9): error CS1929: 'long' does not contain a definition for 'U64' and the best extension method overload 'C.U64(ulong)' requires a receiver of type 'ulong' // 10L.U64(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "10L").WithArguments("long", "U64", "C.U64(ulong)", "ulong").WithLocation(32, 9)); } [Fact] public void SkipConstantExpressionNullableConversionsForThisArgument() { var source = @"static class C { static void S08(this sbyte? arg) { } static void S16(this short? arg) { } static void S32(this int? arg) { } static void S64(this long? arg) { } static void U08(this byte? arg) { } static void U16(this ushort? arg) { } static void U32(this uint? arg) { } static void U64(this ulong? arg) { } static void Main() { S08(1); S16(2); S32(3); S64(4); U08(5); U16(6); U32(7); U64(8); 1.S08(); 2.S16(); 3.S32(); 4.S64(); 5.U08(); 6.U16(); 7.U32(); 8.U64(); S64(9L); U64(10L); 9L.S64(); 10L.U64(); } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }); comp.VerifyDiagnostics( // (21,9): error CS1929: 'int' does not contain a definition for 'S08' and the best extension method overload 'C.S08(sbyte?)' requires a receiver of type 'sbyte?' // 1.S08(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "1").WithArguments("int", "S08", "C.S08(sbyte?)", "sbyte?").WithLocation(21, 9), // (22,9): error CS1929: 'int' does not contain a definition for 'S16' and the best extension method overload 'C.S16(short?)' requires a receiver of type 'short?' // 2.S16(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "2").WithArguments("int", "S16", "C.S16(short?)", "short?").WithLocation(22, 9), // (23,9): error CS1929: 'int' does not contain a definition for 'S32' and the best extension method overload 'C.S32(int?)' requires a receiver of type 'int?' // 3.S32(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "3").WithArguments("int", "S32", "C.S32(int?)", "int?").WithLocation(23, 9), // (24,9): error CS1929: 'int' does not contain a definition for 'S64' and the best extension method overload 'C.S64(long?)' requires a receiver of type 'long?' // 4.S64(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "4").WithArguments("int", "S64", "C.S64(long?)", "long?").WithLocation(24, 9), // (25,9): error CS1929: 'int' does not contain a definition for 'U08' and the best extension method overload 'C.U08(byte?)' requires a receiver of type 'byte?' // 5.U08(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "5").WithArguments("int", "U08", "C.U08(byte?)", "byte?").WithLocation(25, 9), // (26,9): error CS1929: 'int' does not contain a definition for 'U16' and the best extension method overload 'C.U16(ushort?)' requires a receiver of type 'ushort?' // 6.U16(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "6").WithArguments("int", "U16", "C.U16(ushort?)", "ushort?").WithLocation(26, 9), // (27,9): error CS1929: 'int' does not contain a definition for 'U32' and the best extension method overload 'C.U32(uint?)' requires a receiver of type 'uint?' // 7.U32(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "7").WithArguments("int", "U32", "C.U32(uint?)", "uint?").WithLocation(27, 9), // (28,9): error CS1929: 'int' does not contain a definition for 'U64' and the best extension method overload 'C.U64(ulong?)' requires a receiver of type 'ulong?' // 8.U64(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "8").WithArguments("int", "U64", "C.U64(ulong?)", "ulong?").WithLocation(28, 9), // (31,9): error CS1929: 'long' does not contain a definition for 'S64' and the best extension method overload 'C.S64(long?)' requires a receiver of type 'long?' // 9L.S64(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "9L").WithArguments("long", "S64", "C.S64(long?)", "long?").WithLocation(31, 9), // (32,9): error CS1929: 'long' does not contain a definition for 'U64' and the best extension method overload 'C.U64(ulong?)' requires a receiver of type 'ulong?' // 10L.U64(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "10L").WithArguments("long", "U64", "C.U64(ulong?)", "ulong?").WithLocation(32, 9)); } [Fact] [WorkItem(434957, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=434957")] public void SkipUserDefinedConversionsForThisArgument() { var source = @"class A { public static implicit operator B(A a) => null; public static implicit operator S(A a) => default(S); } class B { } struct S { } static class E { internal static void F(this B b) { } internal static void G(this S? s) { } } class C { static void Main() { var a = new A(); var s = default(S); E.F(a); a.F(); E.G(s); s.G(); E.G(a); a.G(); } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (24,9): error CS1929: 'A' does not contain a definition for 'F' and the best extension method overload 'E.F(B)' requires a receiver of type 'B' // a.F(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "a").WithArguments("A", "F", "E.F(B)", "B"), // (26,9): error CS1929: 'S' does not contain a definition for 'G' and the best extension method overload 'E.G(S?)' requires a receiver of type 'S?' // s.G(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "s").WithArguments("S", "G", "E.G(S?)", "S?").WithLocation(26, 9), // (28,9): error CS1929: 'A' does not contain a definition for 'G' and the best extension method overload 'E.G(S?)' requires a receiver of type 'S?' // a.G(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "a").WithArguments("A", "G", "E.G(S?)", "S?")); } [Fact] [WorkItem(434957, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=434957")] public void SkipUserDefinedConversionsForThisArgument_TupleElements() { var source = @"class A { public static implicit operator B(A a) => null; public static implicit operator S(A a) => default(S); } class B { } struct S { } static class E { internal static void F(this (B, B) t) { } internal static void G(this (B, B)? t) { } internal static void H(this (S, S?) t) { } } class C { static void Main() { var a = new A(); var b = new B(); var s = default(S); E.F((a, b)); (a, b).F(); E.G((b, a)); (b, a).G(); E.H((s, s)); (s, s).H(); } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }); comp.VerifyDiagnostics( // (26,9): error CS1929: '(A, B)' does not contain a definition for 'F' and the best extension method overload 'E.F((B, B))' requires a receiver of type '(B, B)' // (a, b).F(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "(a, b)").WithArguments("(A, B)", "F", "E.F((B, B))", "(B, B)").WithLocation(26, 9), // (28,9): error CS1929: '(B, A)' does not contain a definition for 'G' and the best extension method overload 'E.G((B, B)?)' requires a receiver of type '(B, B)?' // (b, a).G(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "(b, a)").WithArguments("(B, A)", "G", "E.G((B, B)?)", "(B, B)?").WithLocation(28, 9), // (30,9): error CS1929: '(S, S)' does not contain a definition for 'H' and the best extension method overload 'E.H((S, S?))' requires a receiver of type '(S, S?)' // (s, s).H(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "(s, s)").WithArguments("(S, S)", "H", "E.H((S, S?))", "(S, S?)").WithLocation(30, 9)); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols { public class ConversionTests : CSharpTestBase { [Fact] public void Test1() { var mscorlibRef = TestMetadata.Net40.mscorlib; var compilation = CSharpCompilation.Create("Test", references: new MetadataReference[] { mscorlibRef }); var sys = compilation.GlobalNamespace.ChildNamespace("System"); Conversions c = new BuckStopsHereBinder(compilation).Conversions; var types = new TypeSymbol[] { sys.ChildType("Object"), sys.ChildType("String"), sys.ChildType("Array"), sys.ChildType("Int64"), sys.ChildType("UInt64"), sys.ChildType("Int32"), sys.ChildType("UInt32"), sys.ChildType("Int16"), sys.ChildType("UInt16"), sys.ChildType("SByte"), sys.ChildType("Byte"), sys.ChildType("Double"), sys.ChildType("Single"), sys.ChildType("Decimal"), sys.ChildType("Char"), sys.ChildType("Nullable", 1).Construct(sys.ChildType("Int64")), sys.ChildType("Nullable", 1).Construct(sys.ChildType("UInt64")), sys.ChildType("Nullable", 1).Construct(sys.ChildType("Int32")), sys.ChildType("Nullable", 1).Construct(sys.ChildType("UInt32")), sys.ChildType("Nullable", 1).Construct(sys.ChildType("Int16")), sys.ChildType("Nullable", 1).Construct(sys.ChildType("UInt16")), sys.ChildType("Nullable", 1).Construct(sys.ChildType("SByte")), sys.ChildType("Nullable", 1).Construct(sys.ChildType("Byte")), sys.ChildType("Nullable", 1).Construct(sys.ChildType("Double")), sys.ChildType("Nullable", 1).Construct(sys.ChildType("Single")), sys.ChildType("Nullable", 1).Construct(sys.ChildType("Decimal")), sys.ChildType("Nullable", 1).Construct(sys.ChildType("Char")), sys.ChildType("Exception"), sys.ChildNamespace("Collections").ChildType("IEnumerable"), sys.ChildNamespace("Collections").ChildNamespace("Generic").ChildType("IEnumerable", 1).Construct(sys.ChildType("Object")), sys.ChildNamespace("Collections").ChildNamespace("Generic").ChildType("IEnumerable", 1).Construct(sys.ChildType("String")), sys.ChildNamespace("Collections").ChildNamespace("Generic").ChildType("IEnumerable", 1).Construct(sys.ChildType("Char")), compilation.CreateArrayTypeSymbol(sys.ChildType("String")), compilation.CreateArrayTypeSymbol(sys.ChildType("Object")), sys.ChildNamespace("Collections").ChildNamespace("Generic").ChildType("IList", 1).Construct(sys.ChildType("String")), sys.ChildNamespace("Collections").ChildNamespace("Generic").ChildType("IList", 1).Construct(sys.ChildType("Object")), sys.ChildType("ArgumentException"), sys.ChildType("Delegate"), sys.ChildType("Func", 2).Construct(sys.ChildType("Exception"), sys.ChildType("Exception")), sys.ChildType("Func", 2).Construct(sys.ChildType("ArgumentException"), sys.ChildType("Object")), sys.ChildNamespace("Runtime").ChildNamespace("Serialization").ChildType("ISerializable"), sys.ChildType("IComparable", 0), }; const ConversionKind Non = ConversionKind.NoConversion; const ConversionKind Idn = ConversionKind.Identity; const ConversionKind Inm = ConversionKind.ImplicitNumeric; const ConversionKind Inl = ConversionKind.ImplicitNullable; const ConversionKind Irf = ConversionKind.ImplicitReference; const ConversionKind Box = ConversionKind.Boxing; const ConversionKind Xrf = ConversionKind.ExplicitReference; const ConversionKind Ubx = ConversionKind.Unboxing; const ConversionKind Xnl = ConversionKind.ExplicitNullable; const ConversionKind Xnm = ConversionKind.ExplicitNumeric; ConversionKind[,] conversions = { // from obj str arr i64 u64 i32 u32 i16 u16 i08 u08 r64 r32 dec chr ni64 nu64 ni32 nu32 ni16 nu16 ni8 nu8 nr64 nr32 ndc nch exc ien ieo ies iec ars aro ils ilo aex del fee fao ser cmp // to: /*obj*/ { Idn, Irf, Irf, Box, Box, Box, Box, Box, Box, Box, Box, Box, Box, Box, Box, Box, Box, Box, Box, Box, Box, Box, Box, Box, Box, Box, Box, Irf, Irf, Irf, Irf, Irf, Irf, Irf, Irf, Irf, Irf, Irf, Irf, Irf, Irf, Irf }, /*str*/ { Xrf, Idn, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Xrf, Non, Non, Xrf, Non, Non, Non, Non, Non, Non, Non, Non, Non, Xrf }, /*arr*/ { Xrf, Non, Idn, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Xrf, Xrf, Xrf, Xrf, Irf, Irf, Xrf, Xrf, Non, Non, Non, Non, Xrf, Xrf }, /*i64*/ { Ubx, Non, Non, Idn, Xnm, Inm, Inm, Inm, Inm, Inm, Inm, Xnm, Xnm, Xnm, Inm, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Ubx }, /*u64*/ { Ubx, Non, Non, Xnm, Idn, Xnm, Inm, Xnm, Inm, Xnm, Inm, Xnm, Xnm, Xnm, Inm, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Ubx }, /*i32*/ { Ubx, Non, Non, Xnm, Xnm, Idn, Xnm, Inm, Inm, Inm, Inm, Xnm, Xnm, Xnm, Inm, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Ubx }, /*u32*/ { Ubx, Non, Non, Xnm, Xnm, Xnm, Idn, Xnm, Inm, Xnm, Inm, Xnm, Xnm, Xnm, Inm, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Ubx }, /*i16*/ { Ubx, Non, Non, Xnm, Xnm, Xnm, Xnm, Idn, Xnm, Inm, Inm, Xnm, Xnm, Xnm, Xnm, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Ubx }, /*u16*/ { Ubx, Non, Non, Xnm, Xnm, Xnm, Xnm, Xnm, Idn, Xnm, Inm, Xnm, Xnm, Xnm, Inm, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Ubx }, /*i08*/ { Ubx, Non, Non, Xnm, Xnm, Xnm, Xnm, Xnm, Xnm, Idn, Xnm, Xnm, Xnm, Xnm, Xnm, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Ubx }, /*u08*/ { Ubx, Non, Non, Xnm, Xnm, Xnm, Xnm, Xnm, Xnm, Xnm, Idn, Xnm, Xnm, Xnm, Xnm, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Ubx }, /*r64*/ { Ubx, Non, Non, Inm, Inm, Inm, Inm, Inm, Inm, Inm, Inm, Idn, Inm, Xnm, Inm, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Ubx }, /*r32*/ { Ubx, Non, Non, Inm, Inm, Inm, Inm, Inm, Inm, Inm, Inm, Xnm, Idn, Xnm, Inm, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Ubx }, /*dec*/ { Ubx, Non, Non, Inm, Inm, Inm, Inm, Inm, Inm, Inm, Inm, Xnm, Xnm, Idn, Inm, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Ubx }, /*chr*/ { Ubx, Non, Non, Xnm, Xnm, Xnm, Xnm, Xnm, Xnm, Xnm, Xnm, Xnm, Xnm, Xnm, Idn, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Ubx }, /*ni64*/ { Ubx, Non, Non, Inl, Xnl, Inl, Inl, Inl, Inl, Inl, Inl, Xnl, Xnl, Xnl, Inl, Idn, Xnl, Inl, Inl, Inl, Inl, Inl, Inl, Xnl, Xnl, Xnl, Inl, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Ubx }, /*nu64*/ { Ubx, Non, Non, Xnl, Inl, Xnl, Inl, Xnl, Inl, Xnl, Inl, Xnl, Xnl, Xnl, Inl, Xnl, Idn, Xnl, Inl, Xnl, Inl, Xnl, Inl, Xnl, Xnl, Xnl, Inl, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Ubx }, /*ni32*/ { Ubx, Non, Non, Xnl, Xnl, Inl, Xnl, Inl, Inl, Inl, Inl, Xnl, Xnl, Xnl, Inl, Xnl, Xnl, Idn, Xnl, Inl, Inl, Inl, Inl, Xnl, Xnl, Xnl, Inl, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Ubx }, /*nu32*/ { Ubx, Non, Non, Xnl, Xnl, Xnl, Inl, Xnl, Inl, Xnl, Inl, Xnl, Xnl, Xnl, Inl, Xnl, Xnl, Xnl, Idn, Xnl, Inl, Xnl, Inl, Xnl, Xnl, Xnl, Inl, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Ubx }, /*ni16*/ { Ubx, Non, Non, Xnl, Xnl, Xnl, Xnl, Inl, Xnl, Inl, Inl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Idn, Xnl, Inl, Inl, Xnl, Xnl, Xnl, Xnl, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Ubx }, /*nu16*/ { Ubx, Non, Non, Xnl, Xnl, Xnl, Xnl, Xnl, Inl, Xnl, Inl, Xnl, Xnl, Xnl, Inl, Xnl, Xnl, Xnl, Xnl, Xnl, Idn, Xnl, Inl, Xnl, Xnl, Xnl, Inl, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Ubx }, /*ni8*/ { Ubx, Non, Non, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Inl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Idn, Xnl, Xnl, Xnl, Xnl, Xnl, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Ubx }, /*nu8*/ { Ubx, Non, Non, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Inl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Idn, Xnl, Xnl, Xnl, Xnl, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Ubx }, /*nr64*/ { Ubx, Non, Non, Inl, Inl, Inl, Inl, Inl, Inl, Inl, Inl, Inl, Inl, Xnl, Inl, Inl, Inl, Inl, Inl, Inl, Inl, Inl, Inl, Idn, Inl, Xnl, Inl, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Ubx }, /*nr32*/ { Ubx, Non, Non, Inl, Inl, Inl, Inl, Inl, Inl, Inl, Inl, Xnl, Inl, Xnl, Inl, Inl, Inl, Inl, Inl, Inl, Inl, Inl, Inl, Xnl, Idn, Xnl, Inl, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Ubx }, /*ndc*/ { Ubx, Non, Non, Inl, Inl, Inl, Inl, Inl, Inl, Inl, Inl, Xnl, Xnl, Inl, Inl, Inl, Inl, Inl, Inl, Inl, Inl, Inl, Inl, Xnl, Xnl, Idn, Inl, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Ubx }, /*nch*/ { Ubx, Non, Non, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Inl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Xnl, Idn, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Ubx }, /*exc*/ { Xrf, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Idn, Xrf, Xrf, Xrf, Xrf, Non, Non, Xrf, Xrf, Irf, Non, Non, Non, Xrf, Xrf }, /*ien*/ { Xrf, Irf, Irf, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Xrf, Idn, Irf, Irf, Irf, Irf, Irf, Irf, Irf, Xrf, Xrf, Non, Non, Xrf, Xrf }, /*ieo*/ { Xrf, Non, Xrf, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Xrf, Xrf, Idn, Irf, Xrf, Irf, Irf, Irf, Irf, Xrf, Xrf, Non, Non, Xrf, Xrf }, /*ies*/ { Xrf, Non, Xrf, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Xrf, Xrf, Xrf, Idn, Xrf, Irf, Xrf, Irf, Xrf, Xrf, Xrf, Non, Non, Xrf, Xrf }, /*iec*/ { Xrf, Irf, Xrf, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Xrf, Xrf, Xrf, Xrf, Idn, Non, Non, Xrf, Xrf, Xrf, Xrf, Non, Non, Xrf, Xrf }, /*ars*/ { Xrf, Non, Xrf, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Xrf, Xrf, Xrf, Non, Idn, Xrf, Xrf, Xrf, Non, Non, Non, Non, Non, Non }, /*aro*/ { Xrf, Non, Xrf, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Xrf, Xrf, Xrf, Non, Irf, Idn, Xrf, Xrf, Non, Non, Non, Non, Non, Non }, /*ils*/ { Xrf, Non, Xrf, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Xrf, Xrf, Xrf, Xrf, Xrf, Irf, Xrf, Idn, Xrf, Xrf, Xrf, Non, Non, Xrf, Xrf }, /*ilo*/ { Xrf, Non, Xrf, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Xrf, Xrf, Xrf, Xrf, Xrf, Irf, Irf, Xrf, Idn, Xrf, Xrf, Non, Non, Xrf, Xrf }, /*aex*/ { Xrf, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Xrf, Xrf, Xrf, Xrf, Xrf, Non, Non, Xrf, Xrf, Idn, Non, Non, Non, Xrf, Xrf }, /*del*/ { Xrf, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Xrf, Xrf, Xrf, Xrf, Non, Non, Xrf, Xrf, Non, Idn, Irf, Irf, Xrf, Xrf }, /*fee*/ { Xrf, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Xrf, Idn, Xrf, Xrf, Non }, /*fao*/ { Xrf, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Xrf, Irf, Idn, Xrf, Non }, /*ser*/ { Xrf, Non, Xrf, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Non, Irf, Xrf, Xrf, Xrf, Xrf, Non, Non, Xrf, Xrf, Irf, Irf, Irf, Irf, Idn, Xrf }, /*cmp*/ { Xrf, Irf, Xrf, Box, Box, Box, Box, Box, Box, Box, Box, Box, Box, Box, Box, Box, Box, Box, Box, Box, Box, Box, Box, Box, Box, Box, Box, Xrf, Xrf, Xrf, Xrf, Xrf, Non, Non, Xrf, Xrf, Xrf, Xrf, Non, Non, Xrf, Idn }, }; HashSet<DiagnosticInfo> useSiteDiagnostics = null; for (int i = 0; i < types.Length; ++i) { for (int j = 0; j < types.Length; ++j) { var kind = conversions[i, j]; var result = c.ClassifyConversionFromType(types[j], types[i], ref useSiteDiagnostics); //Assert.Equal doesn't allow a string explanation, so provide one this way. if (kind != result.Kind) { var result2 = c.ClassifyConversionFromType(types[j], types[i], ref useSiteDiagnostics); // set breakpoint here if this test is failing... Assert.True(false, string.Format("Expected {0} but got {1} when converting {2} -> {3}", kind, result, types[j], types[i])); } } } // UNDONE: Not tested yet: // UNDONE: Type parameter reference, boxing and unboxing conversions // UNDONE: User-defined conversions // UNDONE: Dynamic conversions // UNDONE: Enum conversions // UNDONE: Conversions involving expressions: null, lambda, method group } [Fact] public void TestIsSameTypeIgnoringDynamic() { string code = @" class O<T> { public class I<U,V> { static O<object>.I<U,V> g1; static O<dynamic>.I<U,V> g2; } } class X { object f1; dynamic f2; object[] f3; dynamic[] f4; object[,] f5; O<object>.I<int, object> f6; O<dynamic>.I<int, object> f7; O<object>.I<int, dynamic> f8; O<string> f9; O<dynamic> f10; } "; var mscorlibRef = TestMetadata.Net40.mscorlib; var compilation = CSharpCompilation.Create("Test", new[] { Parse(code) }, new[] { mscorlibRef }); var global = compilation.GlobalNamespace; var classX = global.ChildType("X"); var classI = (NamedTypeSymbol)(global.ChildType("O").ChildSymbol("I")); var f1Type = ((FieldSymbol)(classX.ChildSymbol("f1"))).Type; var f2Type = ((FieldSymbol)(classX.ChildSymbol("f2"))).Type; var f3Type = ((FieldSymbol)(classX.ChildSymbol("f3"))).Type; var f4Type = ((FieldSymbol)(classX.ChildSymbol("f4"))).Type; var f5Type = ((FieldSymbol)(classX.ChildSymbol("f5"))).Type; var f6Type = ((FieldSymbol)(classX.ChildSymbol("f6"))).Type; var f7Type = ((FieldSymbol)(classX.ChildSymbol("f7"))).Type; var f8Type = ((FieldSymbol)(classX.ChildSymbol("f8"))).Type; var f9Type = ((FieldSymbol)(classX.ChildSymbol("f9"))).Type; var f10Type = ((FieldSymbol)(classX.ChildSymbol("f10"))).Type; var g1Type = ((FieldSymbol)(classI.ChildSymbol("g1"))).Type; var g2Type = ((FieldSymbol)(classI.ChildSymbol("g2"))).Type; string s = f7Type.ToTestDisplayString(); Assert.False(f1Type.Equals(f2Type)); Assert.True(f1Type.Equals(f2Type, TypeCompareKind.AllIgnoreOptions)); Assert.True(f2Type.Equals(f1Type, TypeCompareKind.AllIgnoreOptions)); Assert.True(f1Type.Equals(f1Type, TypeCompareKind.AllIgnoreOptions)); Assert.True(f2Type.Equals(f2Type, TypeCompareKind.AllIgnoreOptions)); Assert.False(f3Type.Equals(f4Type)); Assert.True(f3Type.Equals(f4Type, TypeCompareKind.AllIgnoreOptions)); Assert.True(f4Type.Equals(f3Type, TypeCompareKind.AllIgnoreOptions)); Assert.False(f4Type.Equals(f5Type, TypeCompareKind.AllIgnoreOptions)); Assert.False(f5Type.Equals(f4Type, TypeCompareKind.AllIgnoreOptions)); Assert.False(f6Type.Equals(f7Type)); Assert.False(f6Type.Equals(f8Type)); Assert.False(f7Type.Equals(f8Type)); Assert.True(f6Type.Equals(f7Type, TypeCompareKind.AllIgnoreOptions)); Assert.True(f7Type.Equals(f6Type, TypeCompareKind.AllIgnoreOptions)); Assert.True(f6Type.Equals(f6Type, TypeCompareKind.AllIgnoreOptions)); Assert.True(f7Type.Equals(f7Type, TypeCompareKind.AllIgnoreOptions)); Assert.True(f8Type.Equals(f7Type, TypeCompareKind.AllIgnoreOptions)); Assert.True(f7Type.Equals(f8Type, TypeCompareKind.AllIgnoreOptions)); Assert.True(f8Type.Equals(f8Type, TypeCompareKind.AllIgnoreOptions)); Assert.True(f7Type.Equals(f7Type, TypeCompareKind.AllIgnoreOptions)); Assert.True(f8Type.Equals(f6Type, TypeCompareKind.AllIgnoreOptions)); Assert.True(f6Type.Equals(f8Type, TypeCompareKind.AllIgnoreOptions)); Assert.True(f8Type.Equals(f8Type, TypeCompareKind.AllIgnoreOptions)); Assert.True(f6Type.Equals(f6Type, TypeCompareKind.AllIgnoreOptions)); Assert.False(f9Type.Equals(f10Type, TypeCompareKind.AllIgnoreOptions)); Assert.False(f10Type.Equals(f9Type, TypeCompareKind.AllIgnoreOptions)); Assert.False(g1Type.Equals(g2Type)); Assert.True(g1Type.Equals(g2Type, TypeCompareKind.AllIgnoreOptions)); Assert.True(g2Type.Equals(g1Type, TypeCompareKind.AllIgnoreOptions)); Assert.True(g1Type.Equals(g1Type, TypeCompareKind.AllIgnoreOptions)); Assert.True(g2Type.Equals(g2Type, TypeCompareKind.AllIgnoreOptions)); } /// <summary> /// ClassifyConversions should ignore custom modifiers: converting between a type and the same type /// with different custom modifiers should be an identity conversion. /// </summary> [Fact] public void TestConversionsWithCustomModifiers() { var text = @" class C { int[] a; } "; var ilAssemblyReference = TestReferences.SymbolsTests.CustomModifiers.Modifiers.dll; var compilation = CreateCompilation(text, new MetadataReference[] { ilAssemblyReference }); compilation.VerifyDiagnostics( // (4,11): warning CS0169: The field 'C.a' is never used // int[] a; Diagnostic(ErrorCode.WRN_UnreferencedField, "a").WithArguments("C.a") ); var classC = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var typeIntArray = classC.GetMember<FieldSymbol>("a").Type; var interfaceI3 = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("I3"); var typeIntArrayWithCustomModifiers = interfaceI3.GetMember<MethodSymbol>("M1").Parameters.Single().Type; Assert.True(typeIntArrayWithCustomModifiers.HasCustomModifiers(flagNonDefaultArraySizesOrLowerBounds: false)); var conv = new BuckStopsHereBinder(compilation).Conversions; HashSet<DiagnosticInfo> useSiteDiagnostics = null; // no custom modifiers to custom modifiers Assert.Equal(ConversionKind.Identity, conv.ClassifyConversionFromType(typeIntArray, typeIntArrayWithCustomModifiers, ref useSiteDiagnostics).Kind); // custom modifiers to no custom modifiers Assert.Equal(ConversionKind.Identity, conv.ClassifyConversionFromType(typeIntArrayWithCustomModifiers, typeIntArray, ref useSiteDiagnostics).Kind); // custom modifiers to custom modifiers Assert.Equal(ConversionKind.Identity, conv.ClassifyConversionFromType(typeIntArrayWithCustomModifiers, typeIntArrayWithCustomModifiers, ref useSiteDiagnostics).Kind); } [WorkItem(529056, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529056")] [WorkItem(529056, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529056")] [Fact()] public void TestConversion_ParenthesizedExpression() { var source = @" using System; public class Program { public static bool Eval(object obj1, object obj2) { if (/*<bind>*/(obj1 != null)/*</bind>*/ && (obj2 != null)) { return true; } return false; } } "; var comp = (Compilation)CreateCompilation(source); var tuple = GetBindingNodeAndModel<ExpressionSyntax>(comp); Assert.Equal(ConversionKind.Identity, tuple.Item2.ClassifyConversion(tuple.Item1, comp.GetSpecialType(SpecialType.System_Boolean)).Kind); } [WorkItem(544571, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544571")] [Fact] public void TestClassifyConversion() { var source = @" using System; class Program { static void M() { } static void M(long l) { } static void M(short s) { } static void M(int i) { } static void Main() { int ii = 0; Console.WriteLine(ii); short jj = 1; Console.WriteLine(jj); string ss = string.Empty; Console.WriteLine(ss); // Perform conversion classification here. } }"; var tree = SyntaxFactory.ParseSyntaxTree(source); var compilation = (Compilation)CSharpCompilation.Create("MyCompilation") .AddReferences(MscorlibRef) .AddSyntaxTrees(tree); var model = compilation.GetSemanticModel(tree); // Get VariableDeclaratorSyntax corresponding to variable 'ii' above. var variableDeclarator = (VariableDeclaratorSyntax)tree.GetCompilationUnitRoot() .FindToken(source.IndexOf("ii", StringComparison.Ordinal)).Parent; // Get TypeSymbol corresponding to above VariableDeclaratorSyntax. ITypeSymbol targetType = ((ILocalSymbol)model.GetDeclaredSymbol(variableDeclarator)).Type; // Perform ClassifyConversion for expressions from within the above SyntaxTree. var sourceExpression1 = (ExpressionSyntax)tree.GetCompilationUnitRoot() .FindToken(source.IndexOf("jj)", StringComparison.Ordinal)).Parent; Conversion conversion = model.ClassifyConversion(sourceExpression1, targetType); Assert.True(conversion.IsImplicit); Assert.True(conversion.IsNumeric); var sourceExpression2 = (ExpressionSyntax)tree.GetCompilationUnitRoot() .FindToken(source.IndexOf("ss)", StringComparison.Ordinal)).Parent; conversion = model.ClassifyConversion(sourceExpression2, targetType); Assert.False(conversion.Exists); // Perform ClassifyConversion for constructed expressions // at the position identified by the comment '// Perform ...' above. ExpressionSyntax sourceExpression3 = SyntaxFactory.IdentifierName("jj"); var position = source.IndexOf("//", StringComparison.Ordinal); conversion = model.ClassifyConversion(position, sourceExpression3, targetType); Assert.True(conversion.IsImplicit); Assert.True(conversion.IsNumeric); ExpressionSyntax sourceExpression4 = SyntaxFactory.IdentifierName("ss"); conversion = model.ClassifyConversion(position, sourceExpression4, targetType); Assert.False(conversion.Exists); ExpressionSyntax sourceExpression5 = SyntaxFactory.ParseExpression("100L"); conversion = model.ClassifyConversion(position, sourceExpression5, targetType); Assert.True(conversion.IsExplicit); Assert.True(conversion.IsNumeric); } #region "Diagnostics" [Fact] public void VarianceRelationFail() { var source = @" delegate void Covariant<out T>(int argument); class B { } class C { } class Program { public static void Main(string[] args) { Covariant<B> cb = null; Covariant<C> cc = (Covariant<C>)cb; } } "; var compilation = CreateCompilation(source); var diagnostics = compilation.GetDiagnostics(); Assert.NotEmpty(diagnostics); } [Fact] public void EnumFromZero() { var source = @" enum Enum { e1, e2 }; class Program { public static void Main(string[] args) { Enum e = (12L - 12); e = e + 1; } } "; var compilation = CreateCompilation(source); var diagnostics = compilation.GetDiagnostics(); Assert.Empty(diagnostics); } [Fact] public void IdentityConversionInvolvingDynamic() { var source = @" interface I1<T> { } interface I2<T, U> { } class Program { public static void Main(string[] args) { I2<I1<dynamic>, I1<object>> i1 = null; I2<I1<object>, I1<dynamic>> i2 = null; i1 = i2; i2 = i1; } } "; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void WrongDirectionVarianceValueType() { var source = @" interface I<out T> { } struct S : I<object> { public void M() { } } class Program { public static void Main(string[] args) { I<string> i = null; S s = (S)i; } } "; var compilation = CreateCompilation(source); var diagnostics = compilation.GetDiagnostics(); Assert.NotEmpty(diagnostics); } [Fact] public void CastInterfaceToNonimplementingSealed() { var source = @" interface I1 {} sealed class C1 {} public class Driver { public static void Main() { I1 inter = null; C1 c1 = (C1)inter; } } "; var compilation = CreateCompilation(source); var diagnostics = compilation.GetDiagnostics(); Assert.NotEmpty(diagnostics); } [Fact] public void TestLiteralZeroToNullableEnumConversion() { // Oddly enough, the C# specification categorizes // the conversion from 0 to E? as an implicit enumeration conversion, // not as a nullable conversion. var source = @" class Program { enum E { None } public static void Main() { E? e = 0; System.Console.WriteLine(e); } } "; CreateCompilation(source).VerifyDiagnostics(); } [WorkItem(542540, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542540")] [Fact] public void TestMethodGroupConversionWithOptionalParameter() { var source = @" class C { static void goo(int x = 0) //overload resolution picks this method, but the parameter count doesn't match { System.Action a = goo; } } "; CreateCompilation(source).VerifyDiagnostics( // (6,27): error CS0123: No overload for 'goo' matches delegate 'System.Action' // System.Action a = goo; Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "goo").WithArguments("goo", "System.Action")); } [WorkItem(543119, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543119")] [Fact] public void TestConversion_IntToNullableShort() { var source = @"namespace Test { public class Program { short? Goo() { short? s = 2; return s; } } }"; CreateCompilation(source).VerifyDiagnostics(); } [WorkItem(543450, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543450")] [Fact()] public void TestConversion_IntToByte() { var source = @" class Program { public static void Main() { byte x = 1; int y = 1; x <<= y; } }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void AmbiguousImplicitConversion() { var source = @" public class A { static public implicit operator A(B b) { return default(A); } } public class B { static public implicit operator A(B b) { return default(A); } } class Test { static void Main() { B b = new B(); A a = b; } }"; CreateCompilation(source).VerifyDiagnostics( // (23,15): error CS0457: Ambiguous user defined conversions 'B.implicit operator A(B)' and 'A.implicit operator A(B)' when converting from 'B' to 'A' Diagnostic(ErrorCode.ERR_AmbigUDConv, "b").WithArguments("B.implicit operator A(B)", "A.implicit operator A(B)", "B", "A")); } [Fact] public void AmbiguousImplicitConversionAsExplicit() { var source = @" public class A { static public implicit operator A(B b) { return default(A); } } public class B { static public implicit operator A(B b) { return default(A); } } class Test { static void Main() { B b = new B(); A a = (A)b; } }"; CreateCompilation(source).VerifyDiagnostics( // (23,15): error CS0457: Ambiguous user defined conversions 'B.implicit operator A(B)' and 'A.implicit operator A(B)' when converting from 'B' to 'A' Diagnostic(ErrorCode.ERR_AmbigUDConv, "(A)b").WithArguments("B.implicit operator A(B)", "A.implicit operator A(B)", "B", "A")); } [Fact] public void AmbiguousImplicitConversionGeneric() { var source = @" public class A { static public implicit operator A(B<A> b) { return default(A); } } public class B<T> { static public implicit operator T(B<T> b) { return default(T); } } class C { static void Main() { B<A> b = new B<A>(); A a = b; } }"; CreateCompilation(source).VerifyDiagnostics( // (23,15): error CS0457: Ambiguous user defined conversions 'B<A>.implicit operator A(B<A>)' and 'A.implicit operator A(B<A>)' when converting from 'B<A>' to 'A' Diagnostic(ErrorCode.ERR_AmbigUDConv, "b").WithArguments("B<A>.implicit operator A(B<A>)", "A.implicit operator A(B<A>)", "B<A>", "A")); } [Fact] public void AmbiguousExplicitConversion() { var source = @" public class A { static public explicit operator A(B b) { return default(A); } } public class B { static public explicit operator A(B b) { return default(A); } } class Test { static void Main() { B b = new B(); A a = (A)b; } }"; CreateCompilation(source).VerifyDiagnostics( // (23,15): error CS0457: Ambiguous user defined conversions 'B.explicit operator A(B)' and 'A.explicit operator A(B)' when converting from 'B' to 'A' Diagnostic(ErrorCode.ERR_AmbigUDConv, "(A)b").WithArguments("B.explicit operator A(B)", "A.explicit operator A(B)", "B", "A")); } [Fact] public void AmbiguousExplicitConversionAsImplicit() { var source = @" public class A { static public explicit operator A(B b) { return default(A); } } public class B { static public explicit operator A(B b) { return default(A); } } class Test { static void Main() { B b = new B(); A a = b; } }"; CreateCompilation(source).VerifyDiagnostics( // (23,15): error CS0266: Cannot implicitly convert type 'B' to 'A'. An explicit conversion exists (are you missing a cast?) Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "b").WithArguments("B", "A")); } [Fact] public void AmbiguousImplicitExplicitConversionAsImplicit() { var source = @" public class A { static public implicit operator A(B b) { return default(A); } } public class B { static public explicit operator A(B b) { return default(A); } } class Test { static void Main() { B b = new B(); A a = b; } }"; // As in Dev10, we prefer the implicit conversion. CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void AmbiguousImplicitExplicitConversionAsExplicit() { var source = @" public class A { static public implicit operator A(B b) { return default(A); } } public class B { static public explicit operator A(B b) { return default(A); } } class Test { static void Main() { B b = new B(); A a = (A)b; } }"; CreateCompilation(source).VerifyDiagnostics( // (23,15): error CS0457: Ambiguous user defined conversions 'B.explicit operator A(B)' and 'A.implicit operator A(B)' when converting from 'B' to 'A' // A a = (A)b; Diagnostic(ErrorCode.ERR_AmbigUDConv, "(A)b").WithArguments("B.explicit operator A(B)", "A.implicit operator A(B)", "B", "A")); } [Fact] public void NoImplicitConversionsDefaultParameter_01() { var source = @" class C { void Goo(float x = 0.0) { } }"; CreateCompilation(source).VerifyDiagnostics( // (4,20): error CS1750: A value of type 'double' cannot be used as a default parameter because there are no standard conversions to type 'float' // void Goo(float x = 0.0) Diagnostic(ErrorCode.ERR_NoConversionForDefaultParam, "x").WithArguments("double", "float").WithLocation(4, 20) ); } [Fact] public void NoUserDefinedConversionsDefaultParameter1() { var source = @" public class A { static public implicit operator int(A a) { throw null; } } class C { void Goo(int x = default(A)) { } }"; CreateCompilation(source).VerifyDiagnostics( // (12,18): error CS1750: A value of type 'A' cannot be used as a default parameter because there are no standard conversions to type 'int' Diagnostic(ErrorCode.ERR_NoConversionForDefaultParam, "x").WithArguments("A", "int")); } [Fact] public void NoUserDefinedConversionsDefaultParameter2() { var source = @" public class A { static public implicit operator A(int i) { throw null; } } class C { void Goo(A x = default(int)) { } }"; CreateCompilation(source).VerifyDiagnostics( // (12,16): error CS1750: A value of type 'int' cannot be used as a default parameter because there are no standard conversions to type 'A' Diagnostic(ErrorCode.ERR_NoConversionForDefaultParam, "x").WithArguments("int", "A")); } [Fact] public void NoUserDefinedConversionsDefaultParameter3() { var source = @" class Base { } class Derived : Base { } class A { static public implicit operator Derived(A a) { throw null; } } class C { void Goo(Base b = default(A)) { } }"; CreateCompilation(source).VerifyDiagnostics( // (15,19): error CS1750: A value of type 'A' cannot be used as a default parameter because there are no standard conversions to type 'Base' Diagnostic(ErrorCode.ERR_NoConversionForDefaultParam, "b").WithArguments("A", "Base")); } [Fact] public void NoUserDefinedConversionsIs() { var source = @" using System; public sealed class A { static public implicit operator A(B b) { throw null; } static public implicit operator B(A b) { throw null; } } public sealed class B { } class C { static void Main() { A a = new A(); B b = new B(); Console.WriteLine(a is B); Console.WriteLine(b is A); } }"; CreateCompilation(source).VerifyDiagnostics( // (27,27): warning CS0184: The given expression is never of the provided ('B') type Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "a is B").WithArguments("B"), // (28,27): warning CS0184: The given expression is never of the provided ('A') type Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "b is A").WithArguments("A")); } [Fact] public void NoUserDefinedConversionsAs() { var source = @" using System; public sealed class A { static public implicit operator A(B b) { throw null; } static public implicit operator B(A b) { throw null; } } public sealed class B { } class C { static void Main() { A a = new A(); B b = new B(); Console.WriteLine(a as B); Console.WriteLine(b as A); } }"; CreateCompilation(source).VerifyDiagnostics( // (27,27): error CS0039: Cannot convert type 'A' to 'B' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion Diagnostic(ErrorCode.ERR_NoExplicitBuiltinConv, "a as B").WithArguments("A", "B"), // (28,27): error CS0039: Cannot convert type 'B' to 'A' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion Diagnostic(ErrorCode.ERR_NoExplicitBuiltinConv, "b as A").WithArguments("B", "A")); } [Fact] public void NoUserDefinedConversionsThrow() { var source = @" class C { static void Main() { throw new Convertible(); } } class Convertible { public static implicit operator System.Exception(Convertible c) { throw null; } }"; CreateCompilation(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (6,15): error CS0155: The type caught or thrown must be derived from System.Exception Diagnostic(ErrorCode.ERR_BadExceptionType, "new Convertible()")); CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void NoUserDefinedConversionsCatch1() { var source = @" class C { static void Main() { try { } catch(Convertible) { } } } class Convertible { public static implicit operator System.Exception(Convertible c) { throw null; } }"; CreateCompilation(source).VerifyDiagnostics( // (9,15): error CS0155: The type caught or thrown must be derived from System.Exception Diagnostic(ErrorCode.ERR_BadExceptionType, "Convertible")); } [Fact] public void NoUserDefinedConversionsCatch2() { var source = @" class C { static void Main() { try { } catch (Exception1) { } catch (Exception2) { } } } class Exception1 : System.Exception { } class Exception2 : System.Exception { public static implicit operator Exception1(Exception2 e) { throw null; } }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void NoUserDefinedConversionsCaseLabel1() { var source = @" class C { static void Main() { switch (0) { case default(Convertible): return; } } } class Convertible { public static implicit operator int(Convertible e) { return 0; } }"; CreateCompilation(source).VerifyDiagnostics( // (8,18): error CS0150: A constant value is expected // case default(Convertible): return; Diagnostic(ErrorCode.ERR_ConstantExpected, "default(Convertible)").WithLocation(8, 18) ); } [Fact] public void NoUserDefinedConversionsCaseLabel2() { var source = @" class C { static void Main() { const Convertible c = null; switch (0) { case c: return; } } } class Convertible { public static implicit operator int(Convertible e) { return 0; } }"; CreateCompilation(source).VerifyDiagnostics( // (9,18): error CS0150: A constant value is expected // case c: return; Diagnostic(ErrorCode.ERR_ConstantExpected, "c").WithLocation(9, 18) ); } [Fact] public void NoUserDefinedConversionsUsing() { var il = @" .class public sequential ansi sealed beforefieldinit ConvertibleToIDisposable extends [mscorlib]System.ValueType { .method public hidebysig specialname static class [mscorlib]System.IDisposable op_Implicit(valuetype ConvertibleToIDisposable e) cil managed { ldnull ret } } "; var csharp = @" class C { static void Main() { using (var d = new ConvertibleToIDisposable()) { } } }"; CreateCompilationWithILAndMscorlib40(csharp, il).VerifyDiagnostics( // (6,16): error CS1674: 'ConvertibleToIDisposable': type used in a using statement must be implicitly convertible to 'System.IDisposable'. Diagnostic(ErrorCode.ERR_NoConvToIDisp, "var d = new ConvertibleToIDisposable()").WithArguments("ConvertibleToIDisposable")); } [WorkItem(11221, "DevDiv_Projects/Roslyn")] [Fact] public void OverflowInImplicitConversion() { var source = @"class C { public static explicit operator C(byte x) { return null; } static void Main() { var b = (C)1000M; } }"; CreateCompilation(source).VerifyDiagnostics( // (10,17): error CS0031: Constant value '1000M' cannot be converted to a 'byte' // var b = (C)1000M; Diagnostic(ErrorCode.ERR_ConstOutOfRange, "1000M").WithArguments("1000M", "byte") ); } [WorkItem(529568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529568")] [Fact()] public void AmbiguousConversions() { var source = @" // Tests conversions of generic constructed types - both open and closed. using System; public class A { } public class B { } public class C { } public class G0 { public override string ToString() { return ""G0""; } } public class G1<R> : G0 { public override string ToString() { return string.Format(""G1<{0}>"", typeof(R)); } } public class GS2<R, S> : G1<S> { public override string ToString() { return string.Format(""GS2<{0},{1}>"", typeof(R), typeof(S)); } } public class GS3<R, S, T> : GS2<S, T> { public override string ToString() { return string.Format(""GS3<{0},{1},{2}>"", typeof(R), typeof(S), typeof(T)); } } // Parallel hierarchy. public class H0 { public override string ToString() { return ""H0""; } public static implicit operator G0(H0 h) { Console.Write(""[H0->G0] ""); return new G0(); } } public class H1<R> : H0 { public override string ToString() { return string.Format(""H1<{0}>"", typeof(R)); } public static implicit operator G1<R>(H1<R> h) { Console.Write(""[H1->G1] ""); return new G1<R>(); } } public class HS2<R, S> : H1<S> { public override string ToString() { return string.Format(""HS2<{0},{1}>"", typeof(R), typeof(S)); } public static implicit operator GS2<R,S>(HS2<R,S> h) { Console.Write(""[HS2->GS2] ""); return new GS2<R,S>(); } } public class HS3<R, S, T> : HS2<S, T> { public override string ToString() { return string.Format(""HS3<{0},{1},{2}>"", typeof(R), typeof(S), typeof(T)); } public static implicit operator GS3<R,S,T>(HS3<R,S,T> h) { Console.Write(""[HS3->GS3] ""); return new GS3<R,S,T>(); } } // Complex constructed base types. public class GC2<R, S> : G1<G1<S>> { public override string ToString() { return string.Format(""GC2<{0},{1}>"", typeof(R), typeof(S)); } } public class GC3<R, S, T> : GC2<G1<T>, GC2<R, G1<S>>> { public override string ToString() { return string.Format(""GC3<{0},{1},{2}>"", typeof(R), typeof(S), typeof(T)); } } // Parallel hierarchy. public class HC2<R, S> : H1<G1<S>> { public override string ToString() { return string.Format(""HC2<{0},{1}>"", typeof(R), typeof(S)); } public static implicit operator GC2<R,S>(HC2<R,S> h) { Console.Write(""[HC2->GC2] ""); return new GC2<R,S>(); } } public class HC3<R, S, T> : HC2<G1<T>, GC2<R, G1<S>>> { public override string ToString() { return string.Format(""HC3<{0},{1},{2}>"", typeof(R), typeof(S), typeof(T)); } public static implicit operator GC3<R,S,T>(HC3<R,S,T> h) { Console.Write(""[HC3->GC3] ""); return new GC3<R,S,T>(); } } public class HH2<R, S> : H1<H1<S>> { public override string ToString() { return string.Format(""HH2<{0},{1}>"", typeof(R), typeof(S)); } public static implicit operator GC2<R,S>(HH2<R,S> h) { Console.Write(""[HH2->GC2] ""); return new GC2<R,S>(); } } public class HH3<R, S, T> : HH2<H1<T>, HH2<R, H1<S>>> { public override string ToString() { return string.Format(""HH3<{0},{1},{2}>"", typeof(R), typeof(S), typeof(T)); } public static implicit operator GC3<R,S,T>(HH3<R,S,T> h) { Console.Write(""[HH3->GC3] ""); return new GC3<R,S,T>(); } } public class Test { public static void F0(G0 g) { Console.WriteLine(""F0({0})"", g); } public static void F1<R>(G1<R> g) { Console.WriteLine(""F1<{0}>({1})"", typeof(R), g); } public static void FS2<R,S>(GS2<R, S> g) { Console.WriteLine(""FS2<{0},{1}>({2})"", typeof(R), typeof(S), g); } public static void FS3<R,S,T>(GS3<R, S, T> g) { Console.WriteLine(""FS3<{0},{1},{2}>({3})"", typeof(R), typeof(S), typeof(T), g); } public static void FC2<R,S>(GC2<R, S> g) { Console.WriteLine(""FC2<{0},{1}>({2})"", typeof(R), typeof(S), g); } public static void FC3<R,S,T>(GC3<R, S, T> g) { Console.WriteLine(""FC3<{0},{1},{2}>({3})"", typeof(R), typeof(S), typeof(T), g); } public static void Main() { Console.WriteLine(""***** Start generic constructed type conversion test""); G0 g0 = new G0(); G1<A> g1a = new G1<A>(); GS2<A, B> gs2ab = new GS2<A, B>(); GS3<A, B, C> gs3abc = new GS3<A, B, C>(); H0 h0 = new H0(); H1<A> h1a = new H1<A>(); HS2<A, B> hs2ab = new HS2<A, B>(); HS3<A, B, C> hs3abc = new HS3<A, B, C>(); GC2<A, B> gc2ab = new GC2<A, B>(); GC3<A, B, C> gc3abc = new GC3<A, B, C>(); HC2<A, B> hc2ab = new HC2<A, B>(); HC3<A, B, C> hc3abc = new HC3<A, B, C>(); HH2<A, B> hh2ab = new HH2<A, B>(); HH3<A, B, C> hh3abc = new HH3<A, B, C>(); // ***** Implicit user defined conversion. // H1<A> -> G0: ambiguous F0(h1a); // HS2<A,B> -> G0: ambiguous F0(hs2ab); // HS3<A,B,C> -> G0: ambiguous F0(hs3abc); // H1<A> -> G1<A> F1(h1a); // HS2<A,B> -> G1<B>: ambiguous F1<B>(hs2ab); // HS3<A,B,C> -> G1<C>: ambiguous F1<C>(hs3abc); // HS2<A,B> -> GS2<A,B> FS2(hs2ab); // HS3<A,B,C> -> GS2<B,C>: ambiguous FS2<B,C>(hs3abc); // HS3<A,B,C> -> GS3<A,B,C> FS3(hs3abc); // * Complex // HC2<A,B> -> G0: ambiguous F0(hc2ab); // HC3<A,B,C> -> G0: ambiguous F0(hc3abc); // HC2<A,B> -> G1<G1<B>>: ambiguous F1<G1<B>>(hc2ab); // HC3<A,B,C> -> G1<G1<GC2<A,G1<B>>>>: ambiguous F1<G1<GC2<A,G1<B>>>>(hc3abc); // HC2<A,B> -> GC2<A,B> FC2(hc2ab); // HC3<A,B,C> -> GC2<G1<C>,GC2<A,G1<B>>>: ambiguous FC2<G1<C>,GC2<A,G1<B>>>(hc3abc); // HC3<A,B,C> -> GC3<A,B,C> FC3(hc3abc); // HH2<A,B> -> G0: ambiguous F0(hh2ab); // HH3<A,B,C> -> G0: ambiguous F0(hh3abc); // HH2<A,B> -> G1<*> F1(hh2ab); // HH3<A,B,C> -> G1<*> F1(hh3abc); // HH3<A,B,C> -> G1<*> F1(hh3abc); // HH2<A,B> -> GC2<A,B> FC2(hh2ab); // HH3<A,B,C> -> GC2<*> FC2(hh3abc); // HH3<A,B,C> -> GC2<*> FC2(hh3abc); // HG3<A,B,C> -> GC3<A,B,C> FC3(hh3abc); Console.WriteLine(""***** End generic constructed type conversion test""); } } "; CreateCompilation(source).VerifyDiagnostics( // (126,12): error CS0457: Ambiguous user defined conversions 'H1<A>.implicit operator G1<A>(H1<A>)' and 'H0.implicit operator G0(H0)' when converting from 'H1<A>' to 'G0' // F0(h1a); Diagnostic(ErrorCode.ERR_AmbigUDConv, "h1a").WithArguments("H1<A>.implicit operator G1<A>(H1<A>)", "H0.implicit operator G0(H0)", "H1<A>", "G0"), // (129,12): error CS0457: Ambiguous user defined conversions 'HS2<A, B>.implicit operator GS2<A, B>(HS2<A, B>)' and 'H1<B>.implicit operator G1<B>(H1<B>)' when converting from 'HS2<A, B>' to 'G0' // F0(hs2ab); Diagnostic(ErrorCode.ERR_AmbigUDConv, "hs2ab").WithArguments("HS2<A, B>.implicit operator GS2<A, B>(HS2<A, B>)", "H1<B>.implicit operator G1<B>(H1<B>)", "HS2<A, B>", "G0"), // (132,12): error CS0457: Ambiguous user defined conversions 'HS3<A, B, C>.implicit operator GS3<A, B, C>(HS3<A, B, C>)' and 'HS2<B, C>.implicit operator GS2<B, C>(HS2<B, C>)' when converting from 'HS3<A, B, C>' to 'G0' // F0(hs3abc); Diagnostic(ErrorCode.ERR_AmbigUDConv, "hs3abc").WithArguments("HS3<A, B, C>.implicit operator GS3<A, B, C>(HS3<A, B, C>)", "HS2<B, C>.implicit operator GS2<B, C>(HS2<B, C>)", "HS3<A, B, C>", "G0"), // (135,9): error CS0411: The type arguments for method 'Test.F1<R>(G1<R>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F1(h1a); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F1").WithArguments("Test.F1<R>(G1<R>)"), // (138,15): error CS0457: Ambiguous user defined conversions 'HS2<A, B>.implicit operator GS2<A, B>(HS2<A, B>)' and 'H1<B>.implicit operator G1<B>(H1<B>)' when converting from 'HS2<A, B>' to 'G1<B>' // F1<B>(hs2ab); Diagnostic(ErrorCode.ERR_AmbigUDConv, "hs2ab").WithArguments("HS2<A, B>.implicit operator GS2<A, B>(HS2<A, B>)", "H1<B>.implicit operator G1<B>(H1<B>)", "HS2<A, B>", "G1<B>"), // (141,15): error CS0457: Ambiguous user defined conversions 'HS3<A, B, C>.implicit operator GS3<A, B, C>(HS3<A, B, C>)' and 'HS2<B, C>.implicit operator GS2<B, C>(HS2<B, C>)' when converting from 'HS3<A, B, C>' to 'G1<C>' // F1<C>(hs3abc); Diagnostic(ErrorCode.ERR_AmbigUDConv, "hs3abc").WithArguments("HS3<A, B, C>.implicit operator GS3<A, B, C>(HS3<A, B, C>)", "HS2<B, C>.implicit operator GS2<B, C>(HS2<B, C>)", "HS3<A, B, C>", "G1<C>"), // (144,9): error CS0411: The type arguments for method 'Test.FS2<R, S>(GS2<R, S>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // FS2(hs2ab); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "FS2").WithArguments("Test.FS2<R, S>(GS2<R, S>)"), // (147,18): error CS0457: Ambiguous user defined conversions 'HS3<A, B, C>.implicit operator GS3<A, B, C>(HS3<A, B, C>)' and 'HS2<B, C>.implicit operator GS2<B, C>(HS2<B, C>)' when converting from 'HS3<A, B, C>' to 'GS2<B, C>' // FS2<B,C>(hs3abc); Diagnostic(ErrorCode.ERR_AmbigUDConv, "hs3abc").WithArguments("HS3<A, B, C>.implicit operator GS3<A, B, C>(HS3<A, B, C>)", "HS2<B, C>.implicit operator GS2<B, C>(HS2<B, C>)", "HS3<A, B, C>", "GS2<B, C>"), // (150,9): error CS0411: The type arguments for method 'Test.FS3<R, S, T>(GS3<R, S, T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // FS3(hs3abc); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "FS3").WithArguments("Test.FS3<R, S, T>(GS3<R, S, T>)"), // (155,12): error CS0457: Ambiguous user defined conversions 'HC2<A, B>.implicit operator GC2<A, B>(HC2<A, B>)' and 'H1<G1<B>>.implicit operator G1<G1<B>>(H1<G1<B>>)' when converting from 'HC2<A, B>' to 'G0' // F0(hc2ab); Diagnostic(ErrorCode.ERR_AmbigUDConv, "hc2ab").WithArguments("HC2<A, B>.implicit operator GC2<A, B>(HC2<A, B>)", "H1<G1<B>>.implicit operator G1<G1<B>>(H1<G1<B>>)", "HC2<A, B>", "G0"), // (158,12): error CS0457: Ambiguous user defined conversions 'HC3<A, B, C>.implicit operator GC3<A, B, C>(HC3<A, B, C>)' and 'HC2<G1<C>, GC2<A, G1<B>>>.implicit operator GC2<G1<C>, GC2<A, G1<B>>>(HC2<G1<C>, GC2<A, G1<B>>>)' when converting from 'HC3<A, B, C>' to 'G0' // F0(hc3abc); Diagnostic(ErrorCode.ERR_AmbigUDConv, "hc3abc").WithArguments("HC3<A, B, C>.implicit operator GC3<A, B, C>(HC3<A, B, C>)", "HC2<G1<C>, GC2<A, G1<B>>>.implicit operator GC2<G1<C>, GC2<A, G1<B>>>(HC2<G1<C>, GC2<A, G1<B>>>)", "HC3<A, B, C>", "G0"), // (161,19): error CS0457: Ambiguous user defined conversions 'HC2<A, B>.implicit operator GC2<A, B>(HC2<A, B>)' and 'H1<G1<B>>.implicit operator G1<G1<B>>(H1<G1<B>>)' when converting from 'HC2<A, B>' to 'G1<G1<B>>' // F1<G1<B>>(hc2ab); Diagnostic(ErrorCode.ERR_AmbigUDConv, "hc2ab").WithArguments("HC2<A, B>.implicit operator GC2<A, B>(HC2<A, B>)", "H1<G1<B>>.implicit operator G1<G1<B>>(H1<G1<B>>)", "HC2<A, B>", "G1<G1<B>>"), // (164,30): error CS0457: Ambiguous user defined conversions 'HC3<A, B, C>.implicit operator GC3<A, B, C>(HC3<A, B, C>)' and 'HC2<G1<C>, GC2<A, G1<B>>>.implicit operator GC2<G1<C>, GC2<A, G1<B>>>(HC2<G1<C>, GC2<A, G1<B>>>)' when converting from 'HC3<A, B, C>' to 'G1<G1<GC2<A, G1<B>>>>' // F1<G1<GC2<A,G1<B>>>>(hc3abc); Diagnostic(ErrorCode.ERR_AmbigUDConv, "hc3abc").WithArguments("HC3<A, B, C>.implicit operator GC3<A, B, C>(HC3<A, B, C>)", "HC2<G1<C>, GC2<A, G1<B>>>.implicit operator GC2<G1<C>, GC2<A, G1<B>>>(HC2<G1<C>, GC2<A, G1<B>>>)", "HC3<A, B, C>", "G1<G1<GC2<A, G1<B>>>>"), // (167,9): error CS0411: The type arguments for method 'Test.FC2<R, S>(GC2<R, S>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // FC2(hc2ab); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "FC2").WithArguments("Test.FC2<R, S>(GC2<R, S>)"), // (170,33): error CS0457: Ambiguous user defined conversions 'HC3<A, B, C>.implicit operator GC3<A, B, C>(HC3<A, B, C>)' and 'HC2<G1<C>, GC2<A, G1<B>>>.implicit operator GC2<G1<C>, GC2<A, G1<B>>>(HC2<G1<C>, GC2<A, G1<B>>>)' when converting from 'HC3<A, B, C>' to 'GC2<G1<C>, GC2<A, G1<B>>>' // FC2<G1<C>,GC2<A,G1<B>>>(hc3abc); Diagnostic(ErrorCode.ERR_AmbigUDConv, "hc3abc").WithArguments("HC3<A, B, C>.implicit operator GC3<A, B, C>(HC3<A, B, C>)", "HC2<G1<C>, GC2<A, G1<B>>>.implicit operator GC2<G1<C>, GC2<A, G1<B>>>(HC2<G1<C>, GC2<A, G1<B>>>)", "HC3<A, B, C>", "GC2<G1<C>, GC2<A, G1<B>>>"), // (173,9): error CS0411: The type arguments for method 'Test.FC3<R, S, T>(GC3<R, S, T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // FC3(hc3abc); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "FC3").WithArguments("Test.FC3<R, S, T>(GC3<R, S, T>)"), // (178,12): error CS0457: Ambiguous user defined conversions 'HH2<A, B>.implicit operator GC2<A, B>(HH2<A, B>)' and 'H1<H1<B>>.implicit operator G1<H1<B>>(H1<H1<B>>)' when converting from 'HH2<A, B>' to 'G0' // F0(hh2ab); Diagnostic(ErrorCode.ERR_AmbigUDConv, "hh2ab").WithArguments("HH2<A, B>.implicit operator GC2<A, B>(HH2<A, B>)", "H1<H1<B>>.implicit operator G1<H1<B>>(H1<H1<B>>)", "HH2<A, B>", "G0"), // (181,12): error CS0457: Ambiguous user defined conversions 'HH3<A, B, C>.implicit operator GC3<A, B, C>(HH3<A, B, C>)' and 'HH2<H1<C>, HH2<A, H1<B>>>.implicit operator GC2<H1<C>, HH2<A, H1<B>>>(HH2<H1<C>, HH2<A, H1<B>>>)' when converting from 'HH3<A, B, C>' to 'G0' // F0(hh3abc); Diagnostic(ErrorCode.ERR_AmbigUDConv, "hh3abc").WithArguments("HH3<A, B, C>.implicit operator GC3<A, B, C>(HH3<A, B, C>)", "HH2<H1<C>, HH2<A, H1<B>>>.implicit operator GC2<H1<C>, HH2<A, H1<B>>>(HH2<H1<C>, HH2<A, H1<B>>>)", "HH3<A, B, C>", "G0"), // (184,9): error CS0411: The type arguments for method 'Test.F1<R>(G1<R>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F1(hh2ab); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F1").WithArguments("Test.F1<R>(G1<R>)"), // (187,9): error CS0411: The type arguments for method 'Test.F1<R>(G1<R>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F1(hh3abc); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F1").WithArguments("Test.F1<R>(G1<R>)"), // (190,9): error CS0411: The type arguments for method 'Test.F1<R>(G1<R>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F1(hh3abc); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F1").WithArguments("Test.F1<R>(G1<R>)"), // (193,9): error CS0411: The type arguments for method 'Test.FC2<R, S>(GC2<R, S>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // FC2(hh2ab); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "FC2").WithArguments("Test.FC2<R, S>(GC2<R, S>)"), // (196,9): error CS0411: The type arguments for method 'Test.FC2<R, S>(GC2<R, S>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // FC2(hh3abc); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "FC2").WithArguments("Test.FC2<R, S>(GC2<R, S>)"), // (199,9): error CS0411: The type arguments for method 'Test.FC2<R, S>(GC2<R, S>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // FC2(hh3abc); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "FC2").WithArguments("Test.FC2<R, S>(GC2<R, S>)"), // (202,9): error CS0411: The type arguments for method 'Test.FC3<R, S, T>(GC3<R, S, T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // FC3(hh3abc); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "FC3").WithArguments("Test.FC3<R, S, T>(GC3<R, S, T>)") //Dev10 //error CS0457: Ambiguous user defined conversions 'H1<A>.implicit operator G1<A>(H1<A>)' and 'H0.implicit operator G0(H0)' when converting from 'H1<A>' to 'G0' //error CS0457: Ambiguous user defined conversions 'HS2<A,B>.implicit operator GS2<A,B>(HS2<A,B>)' and 'H0.implicit operator G0(H0)' when converting from 'HS2<A,B>' to 'G0' //error CS0457: Ambiguous user defined conversions 'HS3<A,B,C>.implicit operator GS3<A,B,C>(HS3<A,B,C>)' and 'H0.implicit operator G0(H0)' when converting from 'HS3<A,B,C>' to 'G0' //error CS0411: The type arguments for method 'Test.F1<R>(G1<R>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. //error CS0457: Ambiguous user defined conversions 'HS2<A,B>.implicit operator GS2<A,B>(HS2<A,B>)' and 'H1<B>.implicit operator G1<B>(H1<B>)' when converting from 'HS2<A,B>' to 'G1<B>' //error CS0457: Ambiguous user defined conversions 'HS3<A,B,C>.implicit operator GS3<A,B,C>(HS3<A,B,C>)' and 'H1<C>.implicit operator G1<C>(H1<C>)' when converting from 'HS3<A,B,C>' to 'G1<C>' //error CS0411: The type arguments for method 'Test.FS2<R,S>(GS2<R,S>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. //error CS0457: Ambiguous user defined conversions 'HS3<A,B,C>.implicit operator GS3<A,B,C>(HS3<A,B,C>)' and 'HS2<B,C>.implicit operator GS2<B,C>(HS2<B,C>)' when converting from 'HS3<A,B,C>' to 'GS2<B,C>' //error CS0411: The type arguments for method 'Test.FS3<R,S,T>(GS3<R,S,T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. //error CS0457: Ambiguous user defined conversions 'HC2<A,B>.implicit operator GC2<A,B>(HC2<A,B>)' and 'H0.implicit operator G0(H0)' when converting from 'HC2<A,B>' to 'G0' //error CS0457: Ambiguous user defined conversions 'HC3<A,B,C>.implicit operator GC3<A,B,C>(HC3<A,B,C>)' and 'H0.implicit operator G0(H0)' when converting from 'HC3<A,B,C>' to 'G0' //error CS0457: Ambiguous user defined conversions 'HC2<A,B>.implicit operator GC2<A,B>(HC2<A,B>)' and 'H1<G1<B>>.implicit operator G1<G1<B>>(H1<G1<B>>)' when converting from 'HC2<A,B>' to 'G1<G1<B>>' //error CS0457: Ambiguous user defined conversions 'HC3<A,B,C>.implicit operator GC3<A,B,C>(HC3<A,B,C>)' and 'H1<G1<GC2<A,G1<B>>>>.implicit operator G1<G1<GC2<A,G1<B>>>>(H1<G1<GC2<A,G1<B>>>>)' when converting from 'HC3<A,B,C>' to 'G1<G1<GC2<A,G1<B>>>>' //error CS0411: The type arguments for method 'Test.FC2<R,S>(GC2<R,S>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. //error CS0457: Ambiguous user defined conversions 'HC3<A,B,C>.implicit operator GC3<A,B,C>(HC3<A,B,C>)' and 'HC2<G1<C>,GC2<A,G1<B>>>.implicit operator GC2<G1<C>,GC2<A,G1<B>>>(HC2<G1<C>,GC2<A,G1<B>>>)' when converting from 'HC3<A,B,C>' to 'GC2<G1<C>,GC2<A,G1<B>>>' //error CS0411: The type arguments for method 'Test.FC3<R,S,T>(GC3<R,S,T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. //error CS0457: Ambiguous user defined conversions 'HH2<A,B>.implicit operator GC2<A,B>(HH2<A,B>)' and 'H0.implicit operator G0(H0)' when converting from 'HH2<A,B>' to 'G0' //error CS0457: Ambiguous user defined conversions 'HH3<A,B,C>.implicit operator GC3<A,B,C>(HH3<A,B,C>)' and 'H0.implicit operator G0(H0)' when converting from 'HH3<A,B,C>' to 'G0' //error CS0411: The type arguments for method 'Test.F1<R>(G1<R>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. //error CS0411: The type arguments for method 'Test.F1<R>(G1<R>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. //error CS0411: The type arguments for method 'Test.F1<R>(G1<R>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. //error CS0411: The type arguments for method 'Test.FC2<R,S>(GC2<R,S>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. //error CS0411: The type arguments for method 'Test.FC2<R,S>(GC2<R,S>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. //error CS0411: The type arguments for method 'Test.FC2<R,S>(GC2<R,S>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. //error CS0411: The type arguments for method 'Test.FC3<R,S,T>(GC3<R,S,T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. ); } [WorkItem(545361, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545361")] [ClrOnlyFact] public void NullableIntToStructViaDecimal() { var source = @" using System; public struct S { public static implicit operator S?(decimal d) { Console.Write(d); return new S(); } static void Test(bool b) { Console.Write(b ? 't' : 'f'); } static void Main() { int? i; S? s; i = 1; // Native compiler allows this, even though this is illegal by the spec. // there must be a standard implicit conversion either from int? to decimal // or from decimal to int? -- but neither of those conversions are implicit. // The native compiler instead checks to see if there is a standard conversion // between int and decimal, which there is. // Roslyn also allows this. // Note that there is a codegen difference between the native compiler and Roslyn // here, though the difference actually makes no difference other than the // Roslyn codegen being less efficient. The Roslyn compiler generates this as: // // start with int? // lifted conversion to decimal? (cannot fail) // explicit conversion to decimal (can fail) // user-defined conversion to S? // explicit conversion to S. // // The native compiler generates this as // // start with int? // explicit conversion to int (can fail) // implicit conversion to decimal // user-defined conversion to S? // explicit conversion to S. // // The native code is better; there's no reason to do the lifted conversion // from int? to decimal? and then just check to see if the decimal? is null; // we could simply check if the int? is null in the first place. // // There are many places where Roslyn's nullable codegen is inefficient and // this is one of them. We will likely fix this in a later milestone. s = (S)i; Test(s != null); // true // Let's try the same thing, but with a null. Whether we use the Roslyn or the // native codegen, we should get an exception. bool threw = false; try { i = null; s = (S)i; } catch { threw = true; } Test(threw); // true // Now we come to an interesting case. // // First off, this should not even be legal, this time for two reasons. First, // because again, there is no explicit standard conversion from int? to decimal. // Second, the native compiler binds this as a lifted conversion, even though // a lifted conversion requires that both the input and output types of the // operator be non-nullable value types; obviously the output type is not a non-nullable // value type. // // Even worse, the native compiler allows this and then generates bad code. It generates // a null check on i, but then forgets to generate a conversion from i.Value to decimal // before doing the call. // // Roslyn matches the native compiler's analysis; it treats this as a lifted conversion // even though it ought not to. Roslyn however gets the codegen correct. // i = null; s = (S?)i; Test(s == null); // Roslyn: true. Native compiler: generates bad code that crashes the CLR. } } "; CompileAndVerify(source, expectedOutput: @"1ttt"); } [ConditionalFact(typeof(ClrOnly), typeof(DesktopOnly))] [WorkItem(545471, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545471")] [WorkItem(18446, "https://github.com/dotnet/roslyn/issues/18446")] public void CheckedConversionsInExpressionTrees() { var source = @" using System; using System.Linq.Expressions; namespace ExpressionTest { public struct MyStruct { public static MyStruct operator +(MyStruct c1, MyStruct c2) { return c1; } public static explicit operator int(MyStruct m) { return 0; } public static void Main() { Expression<Func<MyStruct, MyStruct?, MyStruct?>> eb1 = (c1, c2) => c1 + c2; Expression<Func<MyStruct, MyStruct?, MyStruct?>> eb2 = (c1, c2) => checked(c1 + c2); Expression<Func<MyStruct, MyStruct?, MyStruct?>> eb3 = (c1, c2) => unchecked(c1 + c2); Expression<Func<int?, int, int?>> ee1 = (c1, c2) => c1 + c2; Expression<Func<int?, int, int?>> ee2 = (c1, c2) => checked(c1 + c2); Expression<Func<int?, int, int?>> ee3 = (c1, c2) => unchecked(c1 + c2); object[] tests = new object[] { eb1, eb2, eb3, ee1, ee2, ee3, }; foreach (object test in tests) { Console.WriteLine(test); } } } } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.ReleaseExe); CompileAndVerify(compilation, expectedOutput: @" (c1, c2) => (Convert(c1) + c2) (c1, c2) => (Convert(c1) + c2) (c1, c2) => (Convert(c1) + c2) (c1, c2) => (c1 + Convert(c2)) (c1, c2) => (c1 + Convert(c2)) (c1, c2) => (c1 + Convert(c2)) "); } [WorkItem(647055, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/647055")] [Fact] public void AmbiguousImplicitExplicitUserDefined() { var source = @" class Program { void Test(int[] a) { C<int> x1 = (C<int>)1; // Expression to type foreach (C<int> x2 in a) { } // Type to type } } class C<T> { public static implicit operator C<T>(T x) { return null; } public static explicit operator C<T>(int x) { return null; } } "; var comp = (Compilation)CreateCompilation(source); comp.VerifyDiagnostics( // (6,21): error CS0457: Ambiguous user defined conversions 'C<int>.explicit operator C<int>(int)' and 'C<int>.implicit operator C<int>(int)' when converting from 'int' to 'C<int>' // C<int> x1 = (C<int>)1; // Expression to type Diagnostic(ErrorCode.ERR_AmbigUDConv, "(C<int>)1").WithArguments("C<int>.explicit operator C<int>(int)", "C<int>.implicit operator C<int>(int)", "int", "C<int>"), // (8,9): error CS0457: Ambiguous user defined conversions 'C<int>.explicit operator C<int>(int)' and 'C<int>.implicit operator C<int>(int)' when converting from 'int' to 'C<int>' // foreach (C<int> x2 in a) { } // Type to type Diagnostic(ErrorCode.ERR_AmbigUDConv, "foreach").WithArguments("C<int>.explicit operator C<int>(int)", "C<int>.implicit operator C<int>(int)", "int", "C<int>")); var destinationType = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("C").Construct(comp.GetSpecialType(SpecialType.System_Int32)); var conversionSymbols = destinationType.GetMembers().OfType<IMethodSymbol>().Where(m => m.MethodKind == MethodKind.Conversion); Assert.Equal(2, conversionSymbols.Count()); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var castSyntax = tree.GetRoot().DescendantNodes().OfType<CastExpressionSyntax>().Single(); var castInfo = model.GetSymbolInfo(castSyntax); Assert.Null(castInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, castInfo.CandidateReason); AssertEx.SetEqual(castInfo.CandidateSymbols, conversionSymbols); var forEachSyntax = tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single(); var memberModel = ((CSharpSemanticModel)model).GetMemberModel(forEachSyntax); var boundForEach = memberModel.GetBoundNodes(forEachSyntax).OfType<BoundForEachStatement>().Single(); var elementConversion = boundForEach.ElementConversion; Assert.Equal(LookupResultKind.OverloadResolutionFailure, elementConversion.ResultKind); AssertEx.SetEqual(elementConversion.OriginalUserDefinedConversions.GetPublicSymbols(), conversionSymbols); } [WorkItem(715207, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/715207")] [ClrOnlyFact] public void LiftingReturnTypeOfExplicitUserDefinedConversion() { var source = @" class C { char? Test(object o) { return (char?)(BigInteger)o; } } struct BigInteger { public static explicit operator ushort(BigInteger b) { return 0; } }"; CompileAndVerify(source).VerifyIL("C.Test", @" { // Code size 17 (0x11) .maxstack 1 IL_0000: ldarg.1 IL_0001: unbox.any ""BigInteger"" IL_0006: call ""ushort BigInteger.op_Explicit(BigInteger)"" IL_000b: newobj ""char?..ctor(char)"" IL_0010: ret } "); } [WorkItem(737732, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/737732")] [Fact] public void ConsiderSourceExpressionWhenDeterminingBestUserDefinedConversion() { var source = @" public class C { public static explicit operator C(double d) { return null; } public static explicit operator C(byte b) { return null; } } public class Test { C M() { return (C)0; } } "; var comp = (Compilation)CreateCompilation(source); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var syntax = tree.GetRoot().DescendantNodes().OfType<CastExpressionSyntax>().Single(); var symbol = model.GetSymbolInfo(syntax).Symbol; Assert.Equal(SymbolKind.Method, symbol.Kind); var method = (IMethodSymbol)symbol; Assert.Equal(MethodKind.Conversion, method.MethodKind); Assert.Equal(comp.GlobalNamespace.GetMember<INamedTypeSymbol>("C"), method.ContainingType); Assert.Equal(SpecialType.System_Byte, method.Parameters.Single().Type.SpecialType); } [WorkItem(737732, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/737732")] [Fact] public void Repro737732() { var source = @" using System; public struct C { public static explicit operator C(decimal d) { return default(C); } public static explicit operator C(double d) { return default(C); } public static implicit operator C(byte d) { return default(C); } C Test() { return (C)0; } } "; var comp = (Compilation)CreateCompilation(source); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var syntax = tree.GetRoot().DescendantNodes().OfType<CastExpressionSyntax>().Single(); var symbol = model.GetSymbolInfo(syntax).Symbol; Assert.Equal(SymbolKind.Method, symbol.Kind); var method = (IMethodSymbol)symbol; Assert.Equal(MethodKind.Conversion, method.MethodKind); Assert.Equal(comp.GlobalNamespace.GetMember<INamedTypeSymbol>("C"), method.ContainingType); Assert.Equal(SpecialType.System_Byte, method.Parameters.Single().Type.SpecialType); } [WorkItem(742345, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/742345")] [ClrOnlyFact] public void MethodGroupConversion_ContravarianceAndDynamic() { var source = @" delegate void In<in T>(T t); public class C { static void Main() { M(F); } static void F(string s) { } static void M(In<dynamic> f) { System.Console.WriteLine('A'); } // Better, if both are applicable. static void M(In<string> f) { System.Console.WriteLine('B'); } // Actually chosen, since the other isn't applicable. } "; CompileAndVerify(source, expectedOutput: "B"); } [WorkItem(742345, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/742345")] [Fact] public void MethodGroupConversion_CovarianceAndDynamic() { var source = @" delegate T Out<out T>(); public class C { static void Main() { M(F); } static dynamic F() { throw null; } static void M(Out<string> f) { } // Better, if both are applicable. static void M(Out<dynamic> f) { } } "; // The return type of F isn't considered until the delegate compatibility check, // which happens AFTER determining that the method group conversion exists. As // a result, both methods are considered applicable and the "wrong" one is chosen. CreateCompilationWithMscorlib40AndSystemCore(source, parseOptions: TestOptions.WithoutImprovedOverloadCandidates).VerifyDiagnostics( // (8,11): error CS0407: 'dynamic C.F()' has the wrong return type // M(F); Diagnostic(ErrorCode.ERR_BadRetType, "F").WithArguments("C.F()", "dynamic")); // However, we later added a feature that takes the return type into account. CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics(); } [WorkItem(737971, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/737971")] [Fact] public void ConversionsFromExpressions() { var source = @" using System; public enum E { A } public class Q { public static implicit operator Q(Func<int> f) { return null; } } public class R { public static implicit operator R(E e) { return null; } } public class S { public static implicit operator S(byte b) { return null; } } public struct T { public static implicit operator T(string s) { return default(T); } } public struct U { public unsafe static implicit operator U(void* p) { return default(U); } } public struct V { public static implicit operator V(dynamic[] d) { return default(V); } } public class Test { static void Main() { // Anonymous function { Q q; q = () => 1; //CS1660 q = (Q)(() => 1); } // Method group { Q q; q = F; //CS0428 q = (Q)F; } //Enum { R r; r = 0; //CS0029 r = (E)0; } // Numeric constant { S s; s = 0; s = (S)0; } // Null literal { T t; t = null; t = (T)null; } // Pointer unsafe { U u; u = null; u = &u; u = (U)null; u = (U)(&u); } } static int F() { return 0; } } "; // NOTE: It's pretty wacky that some of these implicit UDCs can only be applied via explicit (cast) conversions, // but that's the native behavior. We need to replicate it for back-compat, but most of the strangeness will // not be spec'd. CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (46,17): error CS1660: Cannot convert lambda expression to type 'Q' because it is not a delegate type // q = () => 1; //CS1660 Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "Q"), // (53,17): error CS0428: Cannot convert method group 'F' to non-delegate type 'Q'. Did you intend to invoke the method? // q = F; //CS0428 Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "Q"), // (60,17): error CS0029: Cannot implicitly convert type 'int' to 'R' // r = 0; //CS0029 Diagnostic(ErrorCode.ERR_NoImplicitConv, "0").WithArguments("int", "R")); } [Fact] public void BoxingConversionsForThisArgument() { var source = @"static class E { internal static void F(this object o) { System.Console.WriteLine(o); } } class C { static void Main() { 1.F(); 'c'.F(); ""s"".F(); (1, (2, 3)).F(); } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore( source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, expectedOutput: @"1 c s (1, (2, 3))"); } [Fact] public void SkipNumericConversionsForThisArgument() { var source = @"static class E { internal static void F(this long l) { } internal static void G(this (long, long) t) { } internal static void H(this (object, object) t) { } } class C { static void Main() { int i = 1; var t = (i, i); E.F(i); i.F(); E.G(t); t.G(); E.H(t); t.H(); } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }); comp.VerifyDiagnostics( // (14,9): error CS1929: 'int' does not contain a definition for 'F' and the best extension method overload 'E.F(long)' requires a receiver of type 'long' // i.F(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "i").WithArguments("int", "F", "E.F(long)", "long").WithLocation(14, 9), // (16,9): error CS1929: '(int, int)' does not contain a definition for 'G' and the best extension method overload 'E.G((long, long))' requires a receiver of type '(long, long)' // t.G(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "t").WithArguments("(int, int)", "G", "E.G((long, long))", "(long, long)").WithLocation(16, 9)); } [Fact] public void SkipNullableConversionsForThisArgument() { var source = @"static class E { internal static void F(this int? i) { } internal static void G(this (int, int)? t) { } } class C { static void Main() { int i = 1; var t = (i, i); E.F(i); i.F(); E.F((int?)i); ((int?)i).F(); E.G(t); t.G(); E.G(((int, int)?)t); (((int, int)?)t).G(); } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }); comp.VerifyDiagnostics( // (13,9): error CS1929: 'int' does not contain a definition for 'F' and the best extension method overload 'E.F(int?)' requires a receiver of type 'int?' // i.F(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "i").WithArguments("int", "F", "E.F(int?)", "int?").WithLocation(13, 9), // (17,9): error CS1929: '(int, int)' does not contain a definition for 'G' and the best extension method overload 'E.G((int, int)?)' requires a receiver of type '(int, int)?' // t.G(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "t").WithArguments("(int, int)", "G", "E.G((int, int)?)", "(int, int)?").WithLocation(17, 9)); } [Fact] public void SkipEnumerationConversionsForThisArgument() { var source = @"enum E { } static class C { static void F(this E e) { } static void G(this E? e) { } static void H(this (E, E?) t) { } static void Main() { const E e = default(E); F(e); e.F(); F(0); 0.F(); G(e); e.G(); G((E?)e); ((E?)e).G(); G(0); 0.G(); H((e, e)); (e, e).H(); H((e, (E?)e)); (e, (E?)e).H(); } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }); comp.VerifyDiagnostics( // (15,9): error CS1929: 'int' does not contain a definition for 'F' and the best extension method overload 'C.F(E)' requires a receiver of type 'E' // 0.F(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "0").WithArguments("int", "F", "C.F(E)", "E").WithLocation(15, 9), // (17,9): error CS1929: 'E' does not contain a definition for 'G' and the best extension method overload 'C.G(E?)' requires a receiver of type 'E?' // e.G(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "e").WithArguments("E", "G", "C.G(E?)", "E?").WithLocation(17, 9), // (21,9): error CS1929: 'int' does not contain a definition for 'G' and the best extension method overload 'C.G(E?)' requires a receiver of type 'E?' // 0.G(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "0").WithArguments("int", "G", "C.G(E?)", "E?").WithLocation(21, 9), // (23,9): error CS1929: '(E, E)' does not contain a definition for 'H' and the best extension method overload 'C.H((E, E?))' requires a receiver of type '(E, E?)' // (e, e).H(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "(e, e)").WithArguments("(E, E)", "H", "C.H((E, E?))", "(E, E?)").WithLocation(23, 9)); } [Fact] public void SkipConstantExpressionConversionsForThisArgument() { var source = @"static class C { static void S08(this sbyte arg) { } static void S16(this short arg) { } static void S32(this int arg) { } static void S64(this long arg) { } static void U08(this byte arg) { } static void U16(this ushort arg) { } static void U32(this uint arg) { } static void U64(this ulong arg) { } static void Main() { S08(1); S16(2); S32(3); S64(4); U08(5); U16(6); U32(7); U64(8); 1.S08(); 2.S16(); 3.S32(); 4.S64(); 5.U08(); 6.U16(); 7.U32(); 8.U64(); S64(9L); U64(10L); 9L.S64(); 10L.U64(); } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }); comp.VerifyDiagnostics( // (21,9): error CS1929: 'int' does not contain a definition for 'S08' and the best extension method overload 'C.S08(sbyte)' requires a receiver of type 'sbyte' // 1.S08(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "1").WithArguments("int", "S08", "C.S08(sbyte)", "sbyte").WithLocation(21, 9), // (22,9): error CS1929: 'int' does not contain a definition for 'S16' and the best extension method overload 'C.S16(short)' requires a receiver of type 'short' // 2.S16(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "2").WithArguments("int", "S16", "C.S16(short)", "short").WithLocation(22, 9), // (24,9): error CS1929: 'int' does not contain a definition for 'S64' and the best extension method overload 'C.S64(long)' requires a receiver of type 'long' // 4.S64(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "4").WithArguments("int", "S64", "C.S64(long)", "long").WithLocation(24, 9), // (25,9): error CS1929: 'int' does not contain a definition for 'U08' and the best extension method overload 'C.U08(byte)' requires a receiver of type 'byte' // 5.U08(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "5").WithArguments("int", "U08", "C.U08(byte)", "byte").WithLocation(25, 9), // (26,9): error CS1929: 'int' does not contain a definition for 'U16' and the best extension method overload 'C.U16(ushort)' requires a receiver of type 'ushort' // 6.U16(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "6").WithArguments("int", "U16", "C.U16(ushort)", "ushort").WithLocation(26, 9), // (27,9): error CS1929: 'int' does not contain a definition for 'U32' and the best extension method overload 'C.U32(uint)' requires a receiver of type 'uint' // 7.U32(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "7").WithArguments("int", "U32", "C.U32(uint)", "uint").WithLocation(27, 9), // (28,9): error CS1929: 'int' does not contain a definition for 'U64' and the best extension method overload 'C.U64(ulong)' requires a receiver of type 'ulong' // 8.U64(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "8").WithArguments("int", "U64", "C.U64(ulong)", "ulong").WithLocation(28, 9), // (32,9): error CS1929: 'long' does not contain a definition for 'U64' and the best extension method overload 'C.U64(ulong)' requires a receiver of type 'ulong' // 10L.U64(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "10L").WithArguments("long", "U64", "C.U64(ulong)", "ulong").WithLocation(32, 9)); } [Fact] public void SkipConstantExpressionNullableConversionsForThisArgument() { var source = @"static class C { static void S08(this sbyte? arg) { } static void S16(this short? arg) { } static void S32(this int? arg) { } static void S64(this long? arg) { } static void U08(this byte? arg) { } static void U16(this ushort? arg) { } static void U32(this uint? arg) { } static void U64(this ulong? arg) { } static void Main() { S08(1); S16(2); S32(3); S64(4); U08(5); U16(6); U32(7); U64(8); 1.S08(); 2.S16(); 3.S32(); 4.S64(); 5.U08(); 6.U16(); 7.U32(); 8.U64(); S64(9L); U64(10L); 9L.S64(); 10L.U64(); } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }); comp.VerifyDiagnostics( // (21,9): error CS1929: 'int' does not contain a definition for 'S08' and the best extension method overload 'C.S08(sbyte?)' requires a receiver of type 'sbyte?' // 1.S08(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "1").WithArguments("int", "S08", "C.S08(sbyte?)", "sbyte?").WithLocation(21, 9), // (22,9): error CS1929: 'int' does not contain a definition for 'S16' and the best extension method overload 'C.S16(short?)' requires a receiver of type 'short?' // 2.S16(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "2").WithArguments("int", "S16", "C.S16(short?)", "short?").WithLocation(22, 9), // (23,9): error CS1929: 'int' does not contain a definition for 'S32' and the best extension method overload 'C.S32(int?)' requires a receiver of type 'int?' // 3.S32(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "3").WithArguments("int", "S32", "C.S32(int?)", "int?").WithLocation(23, 9), // (24,9): error CS1929: 'int' does not contain a definition for 'S64' and the best extension method overload 'C.S64(long?)' requires a receiver of type 'long?' // 4.S64(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "4").WithArguments("int", "S64", "C.S64(long?)", "long?").WithLocation(24, 9), // (25,9): error CS1929: 'int' does not contain a definition for 'U08' and the best extension method overload 'C.U08(byte?)' requires a receiver of type 'byte?' // 5.U08(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "5").WithArguments("int", "U08", "C.U08(byte?)", "byte?").WithLocation(25, 9), // (26,9): error CS1929: 'int' does not contain a definition for 'U16' and the best extension method overload 'C.U16(ushort?)' requires a receiver of type 'ushort?' // 6.U16(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "6").WithArguments("int", "U16", "C.U16(ushort?)", "ushort?").WithLocation(26, 9), // (27,9): error CS1929: 'int' does not contain a definition for 'U32' and the best extension method overload 'C.U32(uint?)' requires a receiver of type 'uint?' // 7.U32(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "7").WithArguments("int", "U32", "C.U32(uint?)", "uint?").WithLocation(27, 9), // (28,9): error CS1929: 'int' does not contain a definition for 'U64' and the best extension method overload 'C.U64(ulong?)' requires a receiver of type 'ulong?' // 8.U64(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "8").WithArguments("int", "U64", "C.U64(ulong?)", "ulong?").WithLocation(28, 9), // (31,9): error CS1929: 'long' does not contain a definition for 'S64' and the best extension method overload 'C.S64(long?)' requires a receiver of type 'long?' // 9L.S64(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "9L").WithArguments("long", "S64", "C.S64(long?)", "long?").WithLocation(31, 9), // (32,9): error CS1929: 'long' does not contain a definition for 'U64' and the best extension method overload 'C.U64(ulong?)' requires a receiver of type 'ulong?' // 10L.U64(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "10L").WithArguments("long", "U64", "C.U64(ulong?)", "ulong?").WithLocation(32, 9)); } [Fact] [WorkItem(434957, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=434957")] public void SkipUserDefinedConversionsForThisArgument() { var source = @"class A { public static implicit operator B(A a) => null; public static implicit operator S(A a) => default(S); } class B { } struct S { } static class E { internal static void F(this B b) { } internal static void G(this S? s) { } } class C { static void Main() { var a = new A(); var s = default(S); E.F(a); a.F(); E.G(s); s.G(); E.G(a); a.G(); } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (24,9): error CS1929: 'A' does not contain a definition for 'F' and the best extension method overload 'E.F(B)' requires a receiver of type 'B' // a.F(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "a").WithArguments("A", "F", "E.F(B)", "B"), // (26,9): error CS1929: 'S' does not contain a definition for 'G' and the best extension method overload 'E.G(S?)' requires a receiver of type 'S?' // s.G(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "s").WithArguments("S", "G", "E.G(S?)", "S?").WithLocation(26, 9), // (28,9): error CS1929: 'A' does not contain a definition for 'G' and the best extension method overload 'E.G(S?)' requires a receiver of type 'S?' // a.G(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "a").WithArguments("A", "G", "E.G(S?)", "S?")); } [Fact] [WorkItem(434957, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=434957")] public void SkipUserDefinedConversionsForThisArgument_TupleElements() { var source = @"class A { public static implicit operator B(A a) => null; public static implicit operator S(A a) => default(S); } class B { } struct S { } static class E { internal static void F(this (B, B) t) { } internal static void G(this (B, B)? t) { } internal static void H(this (S, S?) t) { } } class C { static void Main() { var a = new A(); var b = new B(); var s = default(S); E.F((a, b)); (a, b).F(); E.G((b, a)); (b, a).G(); E.H((s, s)); (s, s).H(); } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }); comp.VerifyDiagnostics( // (26,9): error CS1929: '(A, B)' does not contain a definition for 'F' and the best extension method overload 'E.F((B, B))' requires a receiver of type '(B, B)' // (a, b).F(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "(a, b)").WithArguments("(A, B)", "F", "E.F((B, B))", "(B, B)").WithLocation(26, 9), // (28,9): error CS1929: '(B, A)' does not contain a definition for 'G' and the best extension method overload 'E.G((B, B)?)' requires a receiver of type '(B, B)?' // (b, a).G(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "(b, a)").WithArguments("(B, A)", "G", "E.G((B, B)?)", "(B, B)?").WithLocation(28, 9), // (30,9): error CS1929: '(S, S)' does not contain a definition for 'H' and the best extension method overload 'E.H((S, S?))' requires a receiver of type '(S, S?)' // (s, s).H(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "(s, s)").WithArguments("(S, S)", "H", "E.H((S, S?))", "(S, S?)").WithLocation(30, 9)); } #endregion } }
-1
dotnet/roslyn
56,310
Move semantic classification caching down to Editor layer
CyrusNajmabadi
"2021-09-09T23:15:16Z"
"2021-09-10T19:26:25Z"
6e123012d868c56aba8acabfe1ccad1bf8f20b04
7af13b6e3867198cd59c566a905b332888ea1dec
Move semantic classification caching down to Editor layer.
./src/Compilers/CSharp/Test/Semantic/Semantics/UseSiteErrorTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { /// <summary> /// Tests related to use site errors. /// </summary> public class UseSiteErrorTests : CSharpTestBase { [Fact] public void TestFields() { var text = @" public class C { public CSharpErrors.Subclass1 Field; }"; CompileWithMissingReference(text).VerifyDiagnostics(); } [Fact] public void TestOverrideMethodReturnType() { var text = @" class C : CSharpErrors.ClassMethods { public override UnavailableClass ReturnType1() { return null; } public override UnavailableClass[] ReturnType2() { return null; } }"; CompileWithMissingReference(text).VerifyDiagnostics( // (4,21): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // public override UnavailableClass ReturnType1() { return null; } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass"), // (5,21): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // public override UnavailableClass[] ReturnType2() { return null; } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass"), // (4,38): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public override UnavailableClass ReturnType1() { return null; } Diagnostic(ErrorCode.ERR_NoTypeDef, "ReturnType1").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (5,40): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public override UnavailableClass[] ReturnType2() { return null; } Diagnostic(ErrorCode.ERR_NoTypeDef, "ReturnType2").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); } [Fact] public void TestOverrideMethodReturnTypeModOpt() { var text = @" class C : ILErrors.ClassMethods { public override int ReturnType1() { return 0; } public override int[] ReturnType2() { return null; } }"; CompileWithMissingReference(text).VerifyDiagnostics( // (4,25): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public override int ReturnType1() { return 0; } Diagnostic(ErrorCode.ERR_NoTypeDef, "ReturnType1").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (5,27): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public override int[] ReturnType2() { return null; } Diagnostic(ErrorCode.ERR_NoTypeDef, "ReturnType2").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); } [Fact] public void TestOverrideMethodParameterType() { var text = @" class C : CSharpErrors.ClassMethods { public override void ParameterType1(UnavailableClass x) { } public override void ParameterType2(UnavailableClass[] x) { } }"; CompileWithMissingReference(text).VerifyDiagnostics( // (4,41): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // public override void ParameterType1(UnavailableClass x) { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass"), // (5,41): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // public override void ParameterType2(UnavailableClass[] x) { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass")); } [Fact] public void TestOverrideMethodParameterTypeModOpt() { var text = @" class C : ILErrors.ClassMethods { public override void ParameterType1(int x) { } public override void ParameterType2(int[] x) { } }"; CompileWithMissingReference(text).VerifyDiagnostics( // (4,26): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public override void ParameterType1(int x) { } Diagnostic(ErrorCode.ERR_NoTypeDef, "ParameterType1").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (5,26): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public override void ParameterType2(int[] x) { } Diagnostic(ErrorCode.ERR_NoTypeDef, "ParameterType2").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); } [Fact] public void TestImplicitlyImplementMethod() { var text = @" class C : CSharpErrors.InterfaceMethods { public UnavailableClass ReturnType1() { return null; } public UnavailableClass[] ReturnType2() { return null; } public void ParameterType1(UnavailableClass x) { } public void ParameterType2(UnavailableClass[] x) { } }"; CompileWithMissingReference(text).VerifyDiagnostics( // (5,12): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // public UnavailableClass[] ReturnType2() { return null; } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass").WithLocation(5, 12), // (6,32): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // public void ParameterType1(UnavailableClass x) { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass").WithLocation(6, 32), // (7,32): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // public void ParameterType2(UnavailableClass[] x) { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass").WithLocation(7, 32), // (4,12): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // public UnavailableClass ReturnType1() { return null; } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass").WithLocation(4, 12), // (2,11): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // class C : CSharpErrors.InterfaceMethods Diagnostic(ErrorCode.ERR_NoTypeDef, "CSharpErrors.InterfaceMethods").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 11), // (2,11): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // class C : CSharpErrors.InterfaceMethods Diagnostic(ErrorCode.ERR_NoTypeDef, "CSharpErrors.InterfaceMethods").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 11), // (2,11): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // class C : CSharpErrors.InterfaceMethods Diagnostic(ErrorCode.ERR_NoTypeDef, "CSharpErrors.InterfaceMethods").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 11), // (2,11): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // class C : CSharpErrors.InterfaceMethods Diagnostic(ErrorCode.ERR_NoTypeDef, "CSharpErrors.InterfaceMethods").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 11) ); } [Fact] public void TestImplicitlyImplementMethodModOpt() { var text = @" class C : ILErrors.InterfaceMethods { public int ReturnType1() { return 0; } public int[] ReturnType2() { return null; } public void ParameterType1(int x) { } public void ParameterType2(int[] x) { } }"; CompileWithMissingReference(text).VerifyDiagnostics( // (4,16): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public int ReturnType1() { return 0; } Diagnostic(ErrorCode.ERR_NoTypeDef, "ReturnType1").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (5,18): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public int[] ReturnType2() { return null; } Diagnostic(ErrorCode.ERR_NoTypeDef, "ReturnType2").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (6,17): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public void ParameterType1(int x) { } Diagnostic(ErrorCode.ERR_NoTypeDef, "ParameterType1").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (7,17): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public void ParameterType2(int[] x) { } Diagnostic(ErrorCode.ERR_NoTypeDef, "ParameterType2").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); } [Fact] public void TestExplicitlyImplementMethod() { var text = @" class C : CSharpErrors.InterfaceMethods { UnavailableClass CSharpErrors.InterfaceMethods.ReturnType1() { return null; } UnavailableClass[] CSharpErrors.InterfaceMethods.ReturnType2() { return null; } void CSharpErrors.InterfaceMethods.ParameterType1(UnavailableClass x) { } void CSharpErrors.InterfaceMethods.ParameterType2(UnavailableClass[] x) { } }"; CompileWithMissingReference(text).VerifyDiagnostics( // (5,5): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // UnavailableClass[] CSharpErrors.InterfaceMethods.ReturnType2() { return null; } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass").WithLocation(5, 5), // (5,54): error CS0539: 'C.ReturnType2()' in explicit interface declaration is not a member of interface // UnavailableClass[] CSharpErrors.InterfaceMethods.ReturnType2() { return null; } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "ReturnType2").WithArguments("C.ReturnType2()").WithLocation(5, 54), // (6,55): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // void CSharpErrors.InterfaceMethods.ParameterType1(UnavailableClass x) { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass").WithLocation(6, 55), // (6,40): error CS0539: 'C.ParameterType1(UnavailableClass)' in explicit interface declaration is not a member of interface // void CSharpErrors.InterfaceMethods.ParameterType1(UnavailableClass x) { } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "ParameterType1").WithArguments("C.ParameterType1(UnavailableClass)").WithLocation(6, 40), // (7,55): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // void CSharpErrors.InterfaceMethods.ParameterType2(UnavailableClass[] x) { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass").WithLocation(7, 55), // (7,40): error CS0539: 'C.ParameterType2(UnavailableClass[])' in explicit interface declaration is not a member of interface // void CSharpErrors.InterfaceMethods.ParameterType2(UnavailableClass[] x) { } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "ParameterType2").WithArguments("C.ParameterType2(UnavailableClass[])").WithLocation(7, 40), // (4,5): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // UnavailableClass CSharpErrors.InterfaceMethods.ReturnType1() { return null; } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass").WithLocation(4, 5), // (4,52): error CS0539: 'C.ReturnType1()' in explicit interface declaration is not a member of interface // UnavailableClass CSharpErrors.InterfaceMethods.ReturnType1() { return null; } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "ReturnType1").WithArguments("C.ReturnType1()").WithLocation(4, 52), // (2,11): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // class C : CSharpErrors.InterfaceMethods Diagnostic(ErrorCode.ERR_NoTypeDef, "CSharpErrors.InterfaceMethods").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 11), // (2,11): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // class C : CSharpErrors.InterfaceMethods Diagnostic(ErrorCode.ERR_NoTypeDef, "CSharpErrors.InterfaceMethods").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 11), // (2,11): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // class C : CSharpErrors.InterfaceMethods Diagnostic(ErrorCode.ERR_NoTypeDef, "CSharpErrors.InterfaceMethods").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 11), // (2,11): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // class C : CSharpErrors.InterfaceMethods Diagnostic(ErrorCode.ERR_NoTypeDef, "CSharpErrors.InterfaceMethods").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 11) ); } [Fact] public void TestExplicitlyImplementMethodModOpt() { var text = @" class C : ILErrors.InterfaceMethods { int ILErrors.InterfaceMethods.ReturnType1() { return 0; } int[] ILErrors.InterfaceMethods.ReturnType2() { return null; } void ILErrors.InterfaceMethods.ParameterType1(int x) { } void ILErrors.InterfaceMethods.ParameterType2(int[] x) { } }"; CompileWithMissingReference(text).VerifyDiagnostics( // (4,16): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public int ReturnType1() { return 0; } Diagnostic(ErrorCode.ERR_NoTypeDef, "ReturnType1").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (5,18): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public int[] ReturnType2() { return null; } Diagnostic(ErrorCode.ERR_NoTypeDef, "ReturnType2").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (6,17): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public void ParameterType1(int x) { } Diagnostic(ErrorCode.ERR_NoTypeDef, "ParameterType1").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (7,17): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public void ParameterType2(int[] x) { } Diagnostic(ErrorCode.ERR_NoTypeDef, "ParameterType2").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); } [Fact] public void TestOverridePropertyType() { var text = @" class C : CSharpErrors.ClassProperties { public override UnavailableClass Get1 { get { return null; } } public override UnavailableClass[] Get2 { get { return null; } } public override UnavailableClass Set1 { set { } } public override UnavailableClass[] Set2 { set { } } public override UnavailableClass GetSet1 { get { return null; } set { } } public override UnavailableClass[] GetSet2 { get { return null; } set { } } }"; CompileWithMissingReference(text).VerifyDiagnostics( // (4,21): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // public override UnavailableClass Get1 { get { return null; } } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass"), // (5,21): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // public override UnavailableClass[] Get2 { get { return null; } } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass"), // (7,21): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // public override UnavailableClass Set1 { set { } } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass"), // (8,21): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // public override UnavailableClass[] Set2 { set { } } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass"), // (10,21): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // public override UnavailableClass GetSet1 { get { return null; } set { } } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass"), // (11,21): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // public override UnavailableClass[] GetSet2 { get { return null; } set { } } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass"), // (4,38): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public override UnavailableClass Get1 { get { return null; } } Diagnostic(ErrorCode.ERR_NoTypeDef, "Get1").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (5,40): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public override UnavailableClass[] Get2 { get { return null; } } Diagnostic(ErrorCode.ERR_NoTypeDef, "Get2").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (7,38): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public override UnavailableClass Set1 { set { } } Diagnostic(ErrorCode.ERR_NoTypeDef, "Set1").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (8,40): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public override UnavailableClass[] Set2 { set { } } Diagnostic(ErrorCode.ERR_NoTypeDef, "Set2").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (10,38): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public override UnavailableClass GetSet1 { get { return null; } set { } } Diagnostic(ErrorCode.ERR_NoTypeDef, "GetSet1").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (11,40): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public override UnavailableClass[] GetSet2 { get { return null; } set { } } Diagnostic(ErrorCode.ERR_NoTypeDef, "GetSet2").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); } [Fact] public void TestOverridePropertyTypeModOpt() { var text = @" class C : ILErrors.ClassProperties { public override int Get1 { get { return 0; } } public override int[] Get2 { get { return null; } } public override int Set1 { set { } } public override int[] Set2 { set { } } public override int GetSet1 { get { return 0; } set { } } public override int[] GetSet2 { get { return null; } set { } } }"; CompileWithMissingReference(text).VerifyDiagnostics( // (4,25): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public override int Get1 { get { return 0; } } Diagnostic(ErrorCode.ERR_NoTypeDef, "Get1").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (5,27): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public override int[] Get2 { get { return null; } } Diagnostic(ErrorCode.ERR_NoTypeDef, "Get2").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (7,25): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public override int Set1 { set { } } Diagnostic(ErrorCode.ERR_NoTypeDef, "Set1").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (8,27): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public override int[] Set2 { set { } } Diagnostic(ErrorCode.ERR_NoTypeDef, "Set2").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (10,25): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public override int GetSet1 { get { return 0; } set { } } Diagnostic(ErrorCode.ERR_NoTypeDef, "GetSet1").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (11,27): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public override int[] GetSet2 { get { return null; } set { } } Diagnostic(ErrorCode.ERR_NoTypeDef, "GetSet2").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); } [Fact] public void TestImplicitlyImplementProperty() { var text = @" class C : CSharpErrors.InterfaceProperties { public UnavailableClass Get1 { get { return null; } } public UnavailableClass[] Get2 { get { return null; } } public UnavailableClass Set1 { set { } } public UnavailableClass[] Set2 { set { } } public UnavailableClass GetSet1 { get { return null; } set { } } public UnavailableClass[] GetSet2 { get { return null; } set { } } }"; CompileWithMissingReference(text).VerifyDiagnostics( // (5,12): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // public UnavailableClass[] Get2 { get { return null; } } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass").WithLocation(5, 12), // (7,12): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // public UnavailableClass Set1 { set { } } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass").WithLocation(7, 12), // (8,12): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // public UnavailableClass[] Set2 { set { } } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass").WithLocation(8, 12), // (10,12): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // public UnavailableClass GetSet1 { get { return null; } set { } } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass").WithLocation(10, 12), // (11,12): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // public UnavailableClass[] GetSet2 { get { return null; } set { } } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass").WithLocation(11, 12), // (4,12): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // public UnavailableClass Get1 { get { return null; } } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass").WithLocation(4, 12), // (2,11): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // class C : CSharpErrors.InterfaceProperties Diagnostic(ErrorCode.ERR_NoTypeDef, "CSharpErrors.InterfaceProperties").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 11), // (2,11): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // class C : CSharpErrors.InterfaceProperties Diagnostic(ErrorCode.ERR_NoTypeDef, "CSharpErrors.InterfaceProperties").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 11), // (2,11): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // class C : CSharpErrors.InterfaceProperties Diagnostic(ErrorCode.ERR_NoTypeDef, "CSharpErrors.InterfaceProperties").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 11), // (2,11): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // class C : CSharpErrors.InterfaceProperties Diagnostic(ErrorCode.ERR_NoTypeDef, "CSharpErrors.InterfaceProperties").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 11), // (2,11): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // class C : CSharpErrors.InterfaceProperties Diagnostic(ErrorCode.ERR_NoTypeDef, "CSharpErrors.InterfaceProperties").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 11), // (2,11): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // class C : CSharpErrors.InterfaceProperties Diagnostic(ErrorCode.ERR_NoTypeDef, "CSharpErrors.InterfaceProperties").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 11) ); } [Fact] public void TestImplicitlyImplementPropertyModOpt() { var text = @" class C : ILErrors.InterfaceProperties { public int Get1 { get { return 0; } } public int[] Get2 { get { return null; } } public int Set1 { set { } } public int[] Set2 { set { } } public int GetSet1 { get { return 0; } set { } } public int[] GetSet2 { get { return null; } set { } } }"; CompileWithMissingReference(text).VerifyDiagnostics( // (10,44): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public int GetSet1 { get { return 0; } set { } } Diagnostic(ErrorCode.ERR_NoTypeDef, "set").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (11,28): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public int[] GetSet2 { get { return null; } set { } } Diagnostic(ErrorCode.ERR_NoTypeDef, "get").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (11,49): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public int[] GetSet2 { get { return null; } set { } } Diagnostic(ErrorCode.ERR_NoTypeDef, "set").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (4,23): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public int Get1 { get { return 0; } } Diagnostic(ErrorCode.ERR_NoTypeDef, "get").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (5,25): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public int[] Get2 { get { return null; } } Diagnostic(ErrorCode.ERR_NoTypeDef, "get").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (7,23): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public int Set1 { set { } } Diagnostic(ErrorCode.ERR_NoTypeDef, "set").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (8,25): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public int[] Set2 { set { } } Diagnostic(ErrorCode.ERR_NoTypeDef, "set").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (10,26): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public int GetSet1 { get { return 0; } set { } } Diagnostic(ErrorCode.ERR_NoTypeDef, "get").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); } [Fact] public void TestExplicitlyImplementProperty() { var text = @" class C : CSharpErrors.InterfaceProperties { UnavailableClass CSharpErrors.InterfaceProperties.Get1 { get { return null; } } UnavailableClass[] CSharpErrors.InterfaceProperties.Get2 { get { return null; } } UnavailableClass CSharpErrors.InterfaceProperties.Set1 { set { } } UnavailableClass[] CSharpErrors.InterfaceProperties.Set2 { set { } } UnavailableClass CSharpErrors.InterfaceProperties.GetSet1 { get { return null; } set { } } UnavailableClass[] CSharpErrors.InterfaceProperties.GetSet2 { get { return null; } set { } } }"; CompileWithMissingReference(text).VerifyDiagnostics( // (4,5): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // UnavailableClass CSharpErrors.InterfaceProperties.Get1 { get { return null; } } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass").WithLocation(4, 5), // (4,55): error CS0539: 'C.Get1' in explicit interface declaration is not a member of interface // UnavailableClass CSharpErrors.InterfaceProperties.Get1 { get { return null; } } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Get1").WithArguments("C.Get1").WithLocation(4, 55), // (5,5): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // UnavailableClass[] CSharpErrors.InterfaceProperties.Get2 { get { return null; } } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass").WithLocation(5, 5), // (5,57): error CS0539: 'C.Get2' in explicit interface declaration is not a member of interface // UnavailableClass[] CSharpErrors.InterfaceProperties.Get2 { get { return null; } } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Get2").WithArguments("C.Get2").WithLocation(5, 57), // (7,5): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // UnavailableClass CSharpErrors.InterfaceProperties.Set1 { set { } } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass").WithLocation(7, 5), // (7,55): error CS0539: 'C.Set1' in explicit interface declaration is not a member of interface // UnavailableClass CSharpErrors.InterfaceProperties.Set1 { set { } } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Set1").WithArguments("C.Set1").WithLocation(7, 55), // (8,5): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // UnavailableClass[] CSharpErrors.InterfaceProperties.Set2 { set { } } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass").WithLocation(8, 5), // (8,57): error CS0539: 'C.Set2' in explicit interface declaration is not a member of interface // UnavailableClass[] CSharpErrors.InterfaceProperties.Set2 { set { } } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Set2").WithArguments("C.Set2").WithLocation(8, 57), // (10,5): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // UnavailableClass CSharpErrors.InterfaceProperties.GetSet1 { get { return null; } set { } } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass").WithLocation(10, 5), // (10,55): error CS0539: 'C.GetSet1' in explicit interface declaration is not a member of interface // UnavailableClass CSharpErrors.InterfaceProperties.GetSet1 { get { return null; } set { } } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "GetSet1").WithArguments("C.GetSet1").WithLocation(10, 55), // (11,5): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // UnavailableClass[] CSharpErrors.InterfaceProperties.GetSet2 { get { return null; } set { } } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass").WithLocation(11, 5), // (11,57): error CS0539: 'C.GetSet2' in explicit interface declaration is not a member of interface // UnavailableClass[] CSharpErrors.InterfaceProperties.GetSet2 { get { return null; } set { } } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "GetSet2").WithArguments("C.GetSet2").WithLocation(11, 57), // (2,11): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // class C : CSharpErrors.InterfaceProperties Diagnostic(ErrorCode.ERR_NoTypeDef, "CSharpErrors.InterfaceProperties").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 11), // (2,11): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // class C : CSharpErrors.InterfaceProperties Diagnostic(ErrorCode.ERR_NoTypeDef, "CSharpErrors.InterfaceProperties").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 11), // (2,11): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // class C : CSharpErrors.InterfaceProperties Diagnostic(ErrorCode.ERR_NoTypeDef, "CSharpErrors.InterfaceProperties").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 11), // (2,11): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // class C : CSharpErrors.InterfaceProperties Diagnostic(ErrorCode.ERR_NoTypeDef, "CSharpErrors.InterfaceProperties").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 11), // (2,11): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // class C : CSharpErrors.InterfaceProperties Diagnostic(ErrorCode.ERR_NoTypeDef, "CSharpErrors.InterfaceProperties").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 11), // (2,11): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // class C : CSharpErrors.InterfaceProperties Diagnostic(ErrorCode.ERR_NoTypeDef, "CSharpErrors.InterfaceProperties").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 11) ); } [Fact] public void TestExplicitlyImplementPropertyModOpt() { var text = @" class C : ILErrors.InterfaceProperties { int ILErrors.InterfaceProperties.Get1 { get { return 0; } } int[] ILErrors.InterfaceProperties.Get2 { get { return null; } } int ILErrors.InterfaceProperties.Set1 { set { } } int[] ILErrors.InterfaceProperties.Set2 { set { } } int ILErrors.InterfaceProperties.GetSet1 { get { return 0; } set { } } int[] ILErrors.InterfaceProperties.GetSet2 { get { return null; } set { } } }"; CompileWithMissingReference(text).VerifyDiagnostics( // (10,66): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // int ILErrors.InterfaceProperties.GetSet1 { get { return 0; } set { } } Diagnostic(ErrorCode.ERR_NoTypeDef, "set").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (11,50): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // int[] ILErrors.InterfaceProperties.GetSet2 { get { return null; } set { } } Diagnostic(ErrorCode.ERR_NoTypeDef, "get").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (11,71): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // int[] ILErrors.InterfaceProperties.GetSet2 { get { return null; } set { } } Diagnostic(ErrorCode.ERR_NoTypeDef, "set").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (4,45): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // int ILErrors.InterfaceProperties.Get1 { get { return 0; } } Diagnostic(ErrorCode.ERR_NoTypeDef, "get").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (5,47): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // int[] ILErrors.InterfaceProperties.Get2 { get { return null; } } Diagnostic(ErrorCode.ERR_NoTypeDef, "get").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (7,45): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // int ILErrors.InterfaceProperties.Set1 { set { } } Diagnostic(ErrorCode.ERR_NoTypeDef, "set").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (8,47): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // int[] ILErrors.InterfaceProperties.Set2 { set { } } Diagnostic(ErrorCode.ERR_NoTypeDef, "set").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (10,48): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // int ILErrors.InterfaceProperties.GetSet1 { get { return 0; } set { } } Diagnostic(ErrorCode.ERR_NoTypeDef, "get").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); } [Fact] public void TestPropertyAccessorModOpt() { var text = @"class C : ILErrors.ClassProperties { static void M(ILErrors.ClassProperties c) { c.GetSet1 = c.GetSet1; c.GetSet2 = c.GetSet2; c.GetSet3 = c.GetSet3; } void M() { GetSet3 = GetSet3; } }"; CompileWithMissingReference(text).VerifyDiagnostics( // (5,11): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // c.GetSet1 = c.GetSet1; Diagnostic(ErrorCode.ERR_NoTypeDef, "GetSet1").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(5, 11), // (5,23): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // c.GetSet1 = c.GetSet1; Diagnostic(ErrorCode.ERR_NoTypeDef, "GetSet1").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(5, 23), // (6,11): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // c.GetSet2 = c.GetSet2; Diagnostic(ErrorCode.ERR_NoTypeDef, "GetSet2").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 11), // (6,23): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // c.GetSet2 = c.GetSet2; Diagnostic(ErrorCode.ERR_NoTypeDef, "GetSet2").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 23), // (7,11): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // c.GetSet3 = c.GetSet3; Diagnostic(ErrorCode.ERR_NoTypeDef, "GetSet3").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 11), // (7,23): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // c.GetSet3 = c.GetSet3; Diagnostic(ErrorCode.ERR_NoTypeDef, "GetSet3").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 23), // (11,9): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // GetSet3 = GetSet3; Diagnostic(ErrorCode.ERR_NoTypeDef, "GetSet3").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(11, 9), // (11,19): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // GetSet3 = GetSet3; Diagnostic(ErrorCode.ERR_NoTypeDef, "GetSet3").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(11, 19)); } [Fact] public void TestOverrideEventType_FieldLike() { var text = @" class C : CSharpErrors.ClassEvents { public override event UnavailableDelegate Event1; public override event CSharpErrors.EventDelegate<UnavailableClass> Event2; public override event CSharpErrors.EventDelegate<UnavailableClass[]> Event3; void UseEvent() { Event1(); Event2(); Event3(); } }"; CompileWithMissingReference(text).VerifyDiagnostics( // (4,27): error CS0246: The type or namespace name 'UnavailableDelegate' could not be found (are you missing a using directive or an assembly reference?) // public override event UnavailableDelegate Event1; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableDelegate").WithArguments("UnavailableDelegate"), // (5,54): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // public override event CSharpErrors.EventDelegate<UnavailableClass> Event2; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass"), // (6,54): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // public override event CSharpErrors.EventDelegate<UnavailableClass[]> Event3; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass"), // (4,47): error CS0012: The type 'UnavailableDelegate' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public override event UnavailableDelegate Event1; Diagnostic(ErrorCode.ERR_NoTypeDef, "Event1").WithArguments("UnavailableDelegate", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (5,72): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public override event CSharpErrors.EventDelegate<UnavailableClass> Event2; Diagnostic(ErrorCode.ERR_NoTypeDef, "Event2").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (6,74): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public override event CSharpErrors.EventDelegate<UnavailableClass[]> Event3; Diagnostic(ErrorCode.ERR_NoTypeDef, "Event3").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); } [Fact] public void TestOverrideEventType_Custom() { var text = @" class C : CSharpErrors.ClassEvents { public override event UnavailableDelegate Event1 { add { } remove { } } public override event CSharpErrors.EventDelegate<UnavailableClass> Event2 { add { } remove { } } public override event CSharpErrors.EventDelegate<UnavailableClass[]> Event3 { add { } remove { } } }"; CompileWithMissingReference(text).VerifyDiagnostics( // (4,27): error CS0246: The type or namespace name 'UnavailableDelegate' could not be found (are you missing a using directive or an assembly reference?) // public override event UnavailableDelegate Event1; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableDelegate").WithArguments("UnavailableDelegate"), // (5,54): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // public override event CSharpErrors.EventDelegate<UnavailableClass> Event2; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass"), // (6,54): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // public override event CSharpErrors.EventDelegate<UnavailableClass[]> Event3; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass"), // (4,47): error CS0012: The type 'UnavailableDelegate' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public override event UnavailableDelegate Event1; Diagnostic(ErrorCode.ERR_NoTypeDef, "Event1").WithArguments("UnavailableDelegate", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (5,72): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public override event CSharpErrors.EventDelegate<UnavailableClass> Event2; Diagnostic(ErrorCode.ERR_NoTypeDef, "Event2").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (6,74): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public override event CSharpErrors.EventDelegate<UnavailableClass[]> Event3; Diagnostic(ErrorCode.ERR_NoTypeDef, "Event3").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); } [Fact] public void TestOverrideEventTypeModOpt_FieldLike() { var text = @" class C : ILErrors.ClassEvents { public override event System.Action<int[]> Event1; void UseEvent() { Event1(null); } }"; CompileWithMissingReference(text).VerifyDiagnostics( // (4,48): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public override event System.Action<int[]> Event1; Diagnostic(ErrorCode.ERR_NoTypeDef, "Event1").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); } [Fact] public void TestOverrideEventTypeModOpt_Custom() { var text = @" class C : ILErrors.ClassEvents { public override event System.Action<int[]> Event1 { add { } remove { } } }"; CompileWithMissingReference(text).VerifyDiagnostics( // (4,48): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public override event System.Action<int[]> Event1; Diagnostic(ErrorCode.ERR_NoTypeDef, "Event1").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); } [Fact] public void TestImplicitlyImplementEvent_FieldLike() { var text = @" class C : CSharpErrors.InterfaceEvents { public event UnavailableDelegate Event1 = () => { }; public event CSharpErrors.EventDelegate<UnavailableClass> Event2 = () => { }; public event CSharpErrors.EventDelegate<UnavailableClass[]> Event3 = () => { }; }"; CompileWithMissingReference(text).VerifyDiagnostics( // (4,18): error CS0246: The type or namespace name 'UnavailableDelegate' could not be found (are you missing a using directive or an assembly reference?) // public event UnavailableDelegate Event1 = () => { }; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableDelegate").WithArguments("UnavailableDelegate").WithLocation(4, 18), // (5,45): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // public event CSharpErrors.EventDelegate<UnavailableClass> Event2 = () => { }; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass").WithLocation(5, 45), // (6,45): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // public event CSharpErrors.EventDelegate<UnavailableClass[]> Event3 = () => { }; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass").WithLocation(6, 45), // (2,11): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // class C : CSharpErrors.InterfaceEvents Diagnostic(ErrorCode.ERR_NoTypeDef, "CSharpErrors.InterfaceEvents").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 11), // (2,11): error CS0012: The type 'UnavailableDelegate' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // class C : CSharpErrors.InterfaceEvents Diagnostic(ErrorCode.ERR_NoTypeDef, "CSharpErrors.InterfaceEvents").WithArguments("UnavailableDelegate", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 11), // (2,11): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // class C : CSharpErrors.InterfaceEvents Diagnostic(ErrorCode.ERR_NoTypeDef, "CSharpErrors.InterfaceEvents").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 11) ); } [Fact] public void TestImplicitlyImplementEvent_Custom() { var text = @" class C : CSharpErrors.InterfaceEvents { public event UnavailableDelegate Event1 { add { } remove { } } public event CSharpErrors.EventDelegate<UnavailableClass> Event2 { add { } remove { } } public event CSharpErrors.EventDelegate<UnavailableClass[]> Event3 { add { } remove { } } }"; CompileWithMissingReference(text).VerifyDiagnostics( // (4,18): error CS0246: The type or namespace name 'UnavailableDelegate' could not be found (are you missing a using directive or an assembly reference?) // public event UnavailableDelegate Event1 { add { } remove { } } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableDelegate").WithArguments("UnavailableDelegate").WithLocation(4, 18), // (5,45): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // public event CSharpErrors.EventDelegate<UnavailableClass> Event2 { add { } remove { } } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass").WithLocation(5, 45), // (6,45): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // public event CSharpErrors.EventDelegate<UnavailableClass[]> Event3 { add { } remove { } } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass").WithLocation(6, 45), // (2,11): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // class C : CSharpErrors.InterfaceEvents Diagnostic(ErrorCode.ERR_NoTypeDef, "CSharpErrors.InterfaceEvents").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 11), // (2,11): error CS0012: The type 'UnavailableDelegate' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // class C : CSharpErrors.InterfaceEvents Diagnostic(ErrorCode.ERR_NoTypeDef, "CSharpErrors.InterfaceEvents").WithArguments("UnavailableDelegate", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 11), // (2,11): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // class C : CSharpErrors.InterfaceEvents Diagnostic(ErrorCode.ERR_NoTypeDef, "CSharpErrors.InterfaceEvents").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 11) ); } [Fact] public void TestImplicitlyImplementEventModOpt_FieldLike() { var text = @" class C : ILErrors.InterfaceEvents { public event System.Action<int[]> Event1 = x => { }; }"; CompileWithMissingReference(text).VerifyDiagnostics( // (4,39): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public event System.Action<int[]> Event1 = x => { }; Diagnostic(ErrorCode.ERR_NoTypeDef, "Event1").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (4,39): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public event System.Action<int[]> Event1 = x => { }; Diagnostic(ErrorCode.ERR_NoTypeDef, "Event1").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); } [Fact] public void TestImplicitlyImplementEventModOpt_Custom() { var text = @" class C : ILErrors.InterfaceEvents { public event System.Action<int[]> Event1 { add { } remove { } } }"; CompileWithMissingReference(text).VerifyDiagnostics( // (4,56): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public event System.Action<int[]> Event1 { add { } remove { } } Diagnostic(ErrorCode.ERR_NoTypeDef, "remove").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (4,48): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public event System.Action<int[]> Event1 { add { } remove { } } Diagnostic(ErrorCode.ERR_NoTypeDef, "add").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); } [Fact] public void TestExplicitlyImplementEvent_Custom() //NB: can't explicitly implement with field-like { var text = @" class C : CSharpErrors.InterfaceEvents { event UnavailableDelegate CSharpErrors.InterfaceEvents.Event1 { add { } remove { } } event CSharpErrors.EventDelegate<UnavailableClass> CSharpErrors.InterfaceEvents.Event2 { add { } remove { } } event CSharpErrors.EventDelegate<UnavailableClass[]> CSharpErrors.InterfaceEvents.Event3 { add { } remove { } } }"; CompileWithMissingReference(text).VerifyDiagnostics( // (4,11): error CS0246: The type or namespace name 'UnavailableDelegate' could not be found (are you missing a using directive or an assembly reference?) // event UnavailableDelegate CSharpErrors.InterfaceEvents.Event1 { add { } remove { } } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableDelegate").WithArguments("UnavailableDelegate").WithLocation(4, 11), // (4,60): error CS0539: 'C.Event1' in explicit interface declaration is not a member of interface // event UnavailableDelegate CSharpErrors.InterfaceEvents.Event1 { add { } remove { } } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Event1").WithArguments("C.Event1").WithLocation(4, 60), // (5,38): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // event CSharpErrors.EventDelegate<UnavailableClass> CSharpErrors.InterfaceEvents.Event2 { add { } remove { } } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass").WithLocation(5, 38), // (5,85): error CS0539: 'C.Event2' in explicit interface declaration is not a member of interface // event CSharpErrors.EventDelegate<UnavailableClass> CSharpErrors.InterfaceEvents.Event2 { add { } remove { } } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Event2").WithArguments("C.Event2").WithLocation(5, 85), // (6,38): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // event CSharpErrors.EventDelegate<UnavailableClass[]> CSharpErrors.InterfaceEvents.Event3 { add { } remove { } } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass").WithLocation(6, 38), // (6,87): error CS0539: 'C.Event3' in explicit interface declaration is not a member of interface // event CSharpErrors.EventDelegate<UnavailableClass[]> CSharpErrors.InterfaceEvents.Event3 { add { } remove { } } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Event3").WithArguments("C.Event3").WithLocation(6, 87), // (2,11): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // class C : CSharpErrors.InterfaceEvents Diagnostic(ErrorCode.ERR_NoTypeDef, "CSharpErrors.InterfaceEvents").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 11), // (2,11): error CS0012: The type 'UnavailableDelegate' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // class C : CSharpErrors.InterfaceEvents Diagnostic(ErrorCode.ERR_NoTypeDef, "CSharpErrors.InterfaceEvents").WithArguments("UnavailableDelegate", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 11), // (2,11): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // class C : CSharpErrors.InterfaceEvents Diagnostic(ErrorCode.ERR_NoTypeDef, "CSharpErrors.InterfaceEvents").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 11) ); } [Fact] public void TestExplicitlyImplementEventModOpt_Custom() //NB: can't explicitly implement with field-like { var text = @" class C : ILErrors.InterfaceEvents { event System.Action<int[]> ILErrors.InterfaceEvents.Event1 { add { } remove { } } }"; CompileWithMissingReference(text).VerifyDiagnostics( // (4,74): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // event System.Action<int[]> ILErrors.InterfaceEvents.Event1 { add { } remove { } } Diagnostic(ErrorCode.ERR_NoTypeDef, "remove").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (4,66): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // event System.Action<int[]> ILErrors.InterfaceEvents.Event1 { add { } remove { } } Diagnostic(ErrorCode.ERR_NoTypeDef, "add").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); } [Fact] public void TestEventAccess() { var text = @"class C { static void M(CSharpErrors.ClassEvents c, ILErrors.ClassEvents i) { c.Event1 += null; i.Event1 += null; } }"; CompileWithMissingReference(text).VerifyDiagnostics( // (5,11): error CS0012: The type 'UnavailableDelegate' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // c.Event1 += null; Diagnostic(ErrorCode.ERR_NoTypeDef, "Event1").WithArguments("UnavailableDelegate", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (6,11): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // i.Event1 += null; Diagnostic(ErrorCode.ERR_NoTypeDef, "Event1").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); } [Fact] public void TestDelegatesWithNoInvoke() { var text = @"class C { public static T goo<T>(DelegateWithoutInvoke.DelegateGenericFunctionWithoutInvoke<T> del) { return del(""goo""); // will show ERR_InvalidDelegateType instead of ERR_NoSuchMemberOrExtension } public static void Main() { DelegateWithoutInvoke.DelegateSubWithoutInvoke myDelegate1 = bar; myDelegate1.Invoke(""goo""); // will show an ERR_NoSuchMemberOrExtension DelegateWithoutInvoke.DelegateSubWithoutInvoke myDelegate2 = new DelegateWithoutInvoke.DelegateSubWithoutInvoke(myDelegate1); object myDelegate3 = new DelegateWithoutInvoke.DelegateSubWithoutInvoke(bar2); DelegateWithoutInvoke.DelegateSubWithoutInvoke myDelegate4 = x => System.Console.WriteLine(""Hello World""); object myDelegate6 = new DelegateWithoutInvoke.DelegateFunctionWithoutInvoke( x => ""Hello World""); } public static void bar(string p) { System.Console.WriteLine(""Hello World""); } public static void bar2(int p) { System.Console.WriteLine(""Hello World 2""); } }"; var delegatesWithoutInvokeReference = TestReferences.SymbolsTests.DelegateImplementation.DelegatesWithoutInvoke; CreateCompilation(text, new MetadataReference[] { delegatesWithoutInvokeReference }).VerifyDiagnostics( // (7,16): error CS7024: Delegate 'DelegateWithoutInvoke.DelegateGenericFunctionWithoutInvoke<T>' has no invoke method or an invoke method with a return type or parameter types that are not supported. // return del("goo"); // will show ERR_InvalidDelegateType instead of ERR_NoSuchMemberOrExtension Diagnostic(ErrorCode.ERR_InvalidDelegateType, @"del(""goo"")").WithArguments("DelegateWithoutInvoke.DelegateGenericFunctionWithoutInvoke<T>").WithLocation(7, 16), // (13,70): error CS7024: Delegate 'DelegateWithoutInvoke.DelegateSubWithoutInvoke' has no invoke method or an invoke method with a return type or parameter types that are not supported. // DelegateWithoutInvoke.DelegateSubWithoutInvoke myDelegate1 = bar; Diagnostic(ErrorCode.ERR_InvalidDelegateType, "bar").WithArguments("DelegateWithoutInvoke.DelegateSubWithoutInvoke").WithLocation(13, 70), // (14,21): error CS1061: 'DelegateWithoutInvoke.DelegateSubWithoutInvoke' does not contain a definition for 'Invoke' and no accessible extension method 'Invoke' accepting a first argument of type 'DelegateWithoutInvoke.DelegateSubWithoutInvoke' could be found (are you missing a using directive or an assembly reference?) // myDelegate1.Invoke("goo"); // will show an ERR_NoSuchMemberOrExtension Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Invoke").WithArguments("DelegateWithoutInvoke.DelegateSubWithoutInvoke", "Invoke").WithLocation(14, 21), // (15,70): error CS7024: Delegate 'DelegateWithoutInvoke.DelegateSubWithoutInvoke' has no invoke method or an invoke method with a return type or parameter types that are not supported. // DelegateWithoutInvoke.DelegateSubWithoutInvoke myDelegate2 = new DelegateWithoutInvoke.DelegateSubWithoutInvoke(myDelegate1); Diagnostic(ErrorCode.ERR_InvalidDelegateType, "new DelegateWithoutInvoke.DelegateSubWithoutInvoke(myDelegate1)").WithArguments("DelegateWithoutInvoke.DelegateSubWithoutInvoke").WithLocation(15, 70), // (16,30): error CS7024: Delegate 'DelegateWithoutInvoke.DelegateSubWithoutInvoke' has no invoke method or an invoke method with a return type or parameter types that are not supported. // object myDelegate3 = new DelegateWithoutInvoke.DelegateSubWithoutInvoke(bar2); Diagnostic(ErrorCode.ERR_InvalidDelegateType, "new DelegateWithoutInvoke.DelegateSubWithoutInvoke(bar2)").WithArguments("DelegateWithoutInvoke.DelegateSubWithoutInvoke").WithLocation(16, 30), // (17,70): error CS7024: Delegate 'DelegateWithoutInvoke.DelegateSubWithoutInvoke' has no invoke method or an invoke method with a return type or parameter types that are not supported. // DelegateWithoutInvoke.DelegateSubWithoutInvoke myDelegate4 = x => System.Console.WriteLine("Hello World"); Diagnostic(ErrorCode.ERR_InvalidDelegateType, @"x => System.Console.WriteLine(""Hello World"")").WithArguments("DelegateWithoutInvoke.DelegateSubWithoutInvoke").WithLocation(17, 70), // (18,87): error CS7024: Delegate 'DelegateWithoutInvoke.DelegateFunctionWithoutInvoke' has no invoke method or an invoke method with a return type or parameter types that are not supported. // object myDelegate6 = new DelegateWithoutInvoke.DelegateFunctionWithoutInvoke( x => "Hello World"); Diagnostic(ErrorCode.ERR_InvalidDelegateType, @"x => ""Hello World""").WithArguments("DelegateWithoutInvoke.DelegateFunctionWithoutInvoke").WithLocation(18, 87)); } [Fact] public void TestDelegatesWithUseSiteErrors() { var text = @"class C { public static T goo<T>(CSharpErrors.DelegateParameterType3<T> del) { return del.Invoke(""goo""); } public static void Main() { CSharpErrors.DelegateReturnType1 myDelegate1 = bar; myDelegate1(""goo""); CSharpErrors.DelegateReturnType1 myDelegate2 = new CSharpErrors.DelegateReturnType1(myDelegate1); object myDelegate3 = new CSharpErrors.DelegateReturnType1(bar); CSharpErrors.DelegateReturnType1 myDelegate4 = x => System.Console.WriteLine(""Hello World""); object myDelegate6 = new CSharpErrors.DelegateReturnType1( x => ""Hello World""); } public static void bar(string p) { System.Console.WriteLine(""Hello World""); } public static void bar2(int p) { System.Console.WriteLine(""Hello World 2""); } }"; var csharpAssemblyReference = TestReferences.SymbolsTests.UseSiteErrors.CSharp; var ilAssemblyReference = TestReferences.SymbolsTests.UseSiteErrors.IL; CreateCompilation(text, new MetadataReference[] { csharpAssemblyReference, ilAssemblyReference }).VerifyDiagnostics( // (7,16): error CS0012: The type 'UnavailableClass<>' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // return del.Invoke("goo"); Diagnostic(ErrorCode.ERR_NoTypeDef, "del.Invoke").WithArguments("UnavailableClass<>", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 16), // (13,56): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // CSharpErrors.DelegateReturnType1 myDelegate1 = bar; Diagnostic(ErrorCode.ERR_NoTypeDef, "bar").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(13, 56), // (14,9): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // myDelegate1("goo"); Diagnostic(ErrorCode.ERR_NoTypeDef, @"myDelegate1(""goo"")").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(14, 9), // (15,56): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // CSharpErrors.DelegateReturnType1 myDelegate2 = new CSharpErrors.DelegateReturnType1(myDelegate1); Diagnostic(ErrorCode.ERR_NoTypeDef, "new CSharpErrors.DelegateReturnType1(myDelegate1)").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(15, 56), // (16,30): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // object myDelegate3 = new CSharpErrors.DelegateReturnType1(bar); Diagnostic(ErrorCode.ERR_NoTypeDef, "new CSharpErrors.DelegateReturnType1(bar)").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(16, 30), // (17,56): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // CSharpErrors.DelegateReturnType1 myDelegate4 = x => System.Console.WriteLine("Hello World"); Diagnostic(ErrorCode.ERR_NoTypeDef, @"x => System.Console.WriteLine(""Hello World"")").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(17, 56), // (18,68): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // object myDelegate6 = new CSharpErrors.DelegateReturnType1( x => "Hello World"); Diagnostic(ErrorCode.ERR_NoTypeDef, @"x => ""Hello World""").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(18, 68)); } [Fact, WorkItem(531090, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531090")] public void Constructor() { string srcLib1 = @" using System; public sealed class A { public A(int a, Func<string, string> example) {} public A(Func<string, string> example) {} } "; var lib1 = CreateEmptyCompilation( new[] { Parse(srcLib1) }, new[] { TestMetadata.Net20.mscorlib, TestMetadata.Net35.SystemCore }, TestOptions.ReleaseDll.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default)); string srcLib2 = @" class Program { static void Main() { new A(x => x); } } "; var lib2 = CreateEmptyCompilation( new[] { Parse(srcLib2) }, new[] { MscorlibRef, new CSharpCompilationReference(lib1) }, TestOptions.ReleaseDll.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default)); lib2.VerifyDiagnostics( // (6,13): error CS0012: The type 'System.Func<,>' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. // new A(x => x); Diagnostic(ErrorCode.ERR_NoTypeDef, "A").WithArguments("System.Func<,>", "System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")); } [Fact, WorkItem(530974, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530974")] public void SynthesizedInterfaceImplementation() { var xSource = @" public class X {} "; var xRef = CreateCompilation(xSource, assemblyName: "Test").EmitToImageReference(); var libSource = @" public interface I { void Goo(X a); } public class C { public void Goo(X a) { } } "; var lib = CreateCompilation(libSource, new[] { xRef }, assemblyName: "Test"); var mainSource = @" class B : C, I { } "; var main = CreateCompilation(mainSource, new[] { new CSharpCompilationReference(lib) }, assemblyName: "Main"); main.VerifyDiagnostics( // (2,7): error CS7068: Reference to type 'X' claims it is defined in this assembly, but it is not defined in source or any added modules // class B : C, I { } Diagnostic(ErrorCode.ERR_MissingTypeInSource, "B").WithArguments("X")); } [Fact, WorkItem(530974, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530974")] public void NoSynthesizedInterfaceImplementation() { var xSource = @" public class X {} "; var xRef = CreateCompilation(xSource, assemblyName: "X").EmitToImageReference(); var libSource = @" public interface I { void Goo(X a); } public class C { public virtual void Goo(X a) { } } "; var lib = CreateCompilation(libSource, new[] { xRef }, assemblyName: "Lib"); var mainSource = @" class B : C, I { } "; var main = CreateCompilation(mainSource, new[] { new CSharpCompilationReference(lib) }, assemblyName: "Main"); main.VerifyEmitDiagnostics(); } [Fact, WorkItem(530974, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530974")] public void SynthesizedInterfaceImplementation_Indexer() { var xSource = @" public class X {} "; var xRef = CreateCompilation(xSource, assemblyName: "X").EmitToImageReference(); var libSource = @" public interface I { int this[X a] { get; set; } } public class C { public int this[X a] { get { return 1; } set { } } } "; var lib = CreateCompilation(libSource, new[] { xRef }, assemblyName: "Lib"); var mainSource = @" class B : C, I { } "; var main = CreateCompilation(mainSource, new[] { new CSharpCompilationReference(lib) }, assemblyName: "Main"); main.VerifyDiagnostics( // (2,7): error CS0012: The type 'X' is defined in an assembly that is not referenced. You must add a reference to assembly 'X, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // class B : C, I { } Diagnostic(ErrorCode.ERR_NoTypeDef, "B").WithArguments("X", "X, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (2,7): error CS0012: The type 'X' is defined in an assembly that is not referenced. You must add a reference to assembly 'X, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // class B : C, I { } Diagnostic(ErrorCode.ERR_NoTypeDef, "B").WithArguments("X", "X, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); } [Fact, WorkItem(530974, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530974")] public void SynthesizedInterfaceImplementation_ModOpt() { var unavailableRef = TestReferences.SymbolsTests.UseSiteErrors.Unavailable; var ilRef = TestReferences.SymbolsTests.UseSiteErrors.IL; var mainSource = @" class B : ILErrors.ClassEventsNonVirtual, ILErrors.InterfaceEvents { } "; var main = CreateCompilation(mainSource, new[] { ilRef, unavailableRef }); CompileAndVerify(main); } [Fact, WorkItem(530974, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530974")] public void NoSynthesizedInterfaceImplementation_ModOpt() { var unavailableRef = TestReferences.SymbolsTests.UseSiteErrors.Unavailable; var ilRef = TestReferences.SymbolsTests.UseSiteErrors.IL; var mainSource = @" class B : ILErrors.ClassEvents, ILErrors.InterfaceEvents { } "; var main = CreateCompilation(mainSource, new[] { ilRef, unavailableRef }); CompileAndVerify(main); } [Fact, WorkItem(530974, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530974")] public void SynthesizedInterfaceImplementation_ModReq() { var unavailableRef = TestReferences.SymbolsTests.UseSiteErrors.Unavailable; var ilRef = TestReferences.SymbolsTests.UseSiteErrors.IL; var mainSource = @" class B : ILErrors.ModReqClassEventsNonVirtual, ILErrors.ModReqInterfaceEvents { } "; var main = CreateCompilation(mainSource, new[] { ilRef, unavailableRef }); main.VerifyDiagnostics( // (2,7): error CS0570: 'ModReqInterfaceEvents.Event1.remove' is not supported by the language // class B : ILErrors.ModReqClassEventsNonVirtual, ILErrors.ModReqInterfaceEvents { } Diagnostic(ErrorCode.ERR_BindToBogus, "B").WithArguments("ILErrors.ModReqInterfaceEvents.Event1.remove").WithLocation(2, 7), // (2,7): error CS0570: 'ModReqInterfaceEvents.Event1.add' is not supported by the language // class B : ILErrors.ModReqClassEventsNonVirtual, ILErrors.ModReqInterfaceEvents { } Diagnostic(ErrorCode.ERR_BindToBogus, "B").WithArguments("ILErrors.ModReqInterfaceEvents.Event1.add").WithLocation(2, 7) ); } [Fact] public void CompilerGeneratedAttributeNotRequired() { var text = @"class C { public int AProperty { get; set; } }"; var compilation = CreateEmptyCompilation(text).VerifyDiagnostics( // (1,7): error CS0518: Predefined type 'System.Object' is not defined or imported // class C Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "C").WithArguments("System.Object"), // (3,11): error CS0518: Predefined type 'System.Int32' is not defined or imported // public int AProperty { get; set; } Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "int").WithArguments("System.Int32"), // (3,32): error CS0518: Predefined type 'System.Void' is not defined or imported // public int AProperty { get; set; } Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "set;").WithArguments("System.Void"), // (1,7): error CS1729: 'object' does not contain a constructor that takes 0 arguments // class C Diagnostic(ErrorCode.ERR_BadCtorArgCount, "C").WithArguments("object", "0")); foreach (var diag in compilation.GetDiagnostics()) { Assert.DoesNotContain("System.Runtime.CompilerServices.CompilerGeneratedAttribute", diag.GetMessage(), StringComparison.Ordinal); } } [Fact] public void UseSiteErrorsForSwitchSubsumption() { var baseSource = @"public class Base {}"; var baseLib = CreateCompilation(baseSource, assemblyName: "BaseAssembly"); var derivedSource = @"public class Derived : Base {}"; var derivedLib = CreateCompilation(derivedSource, assemblyName: "DerivedAssembly", references: new[] { new CSharpCompilationReference(baseLib) }); var programSource = @" class Program { public static void Main(string[] args) { object o = args; switch (o) { case string s: break; case Derived d: break; } } } "; CreateCompilation(programSource, references: new[] { new CSharpCompilationReference(derivedLib) }).VerifyDiagnostics( // (9,18): error CS0012: The type 'Base' is defined in an assembly that is not referenced. You must add a reference to assembly 'BaseAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // case string s: break; Diagnostic(ErrorCode.ERR_NoTypeDef, "string s").WithArguments("Base", "BaseAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(9, 18) ); } #region Attributes for unsafe code /// <summary> /// Simple test to verify that the infrastructure for the other UnsafeAttributes_* tests works correctly. /// </summary> [Fact] public void UnsafeAttributes_NoErrors() { var text = unsafeAttributeSystemTypes + @" namespace System.Security { public class UnverifiableCodeAttribute : Attribute { } namespace Permissions { public enum SecurityAction { RequestMinimum } public class CodeAccessSecurityAttribute : Attribute { public CodeAccessSecurityAttribute(SecurityAction action) { } } public class SecurityPermissionAttribute : CodeAccessSecurityAttribute { public SecurityPermissionAttribute(SecurityAction action) : base(action) { } public bool SkipVerification { get; set; } } } } "; CompileUnsafeAttributesAndCheckDiagnostics(text, false, // (19,21): error CS0518: Predefined type 'System.Int32' is not defined or imported // public enum SecurityAction Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "SecurityAction").WithArguments("System.Int32")); CompileUnsafeAttributesAndCheckDiagnostics(text, true, // (19,21): error CS0518: Predefined type 'System.Int32' is not defined or imported // public enum SecurityAction Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "SecurityAction").WithArguments("System.Int32")); } /// <summary> /// If the attribute type is missing, just skip emitting the attributes. /// No diagnostics. /// </summary> [Fact] public void UnsafeAttributes_MissingUnverifiableCodeAttribute() { var text = unsafeAttributeSystemTypes + @" namespace System.Security { public class UnverifiableCodeAttribute : Attribute { } namespace Permissions { public enum SecurityAction { RequestMinimum } public class CodeAccessSecurityAttribute : Attribute { public CodeAccessSecurityAttribute(SecurityAction action) { } } public class SecurityPermissionAttribute : CodeAccessSecurityAttribute { public SecurityPermissionAttribute(SecurityAction action) : base(action) { } public bool SkipVerification { get; set; } } } } "; CompileUnsafeAttributesAndCheckDiagnostics(text, false, // (19,21): error CS0518: Predefined type 'System.Int32' is not defined or imported // public enum SecurityAction Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "SecurityAction").WithArguments("System.Int32")); CompileUnsafeAttributesAndCheckDiagnostics(text, true, // (19,21): error CS0518: Predefined type 'System.Int32' is not defined or imported // public enum SecurityAction Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "SecurityAction").WithArguments("System.Int32")); } /// <summary> /// If the attribute type is missing, just skip emitting the attributes. /// No diagnostics. /// </summary> [Fact] public void UnsafeAttributes_MissingSecurityPermissionAttribute() { var text = unsafeAttributeSystemTypes + @" namespace System.Security { public class UnverifiableCodeAttribute : Attribute { } namespace Permissions { public enum SecurityAction { RequestMinimum } } } "; CompileUnsafeAttributesAndCheckDiagnostics(text, false, // (19,21): error CS0518: Predefined type 'System.Int32' is not defined or imported // public enum SecurityAction Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "SecurityAction").WithArguments("System.Int32")); CompileUnsafeAttributesAndCheckDiagnostics(text, true, // (19,21): error CS0518: Predefined type 'System.Int32' is not defined or imported // public enum SecurityAction Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "SecurityAction").WithArguments("System.Int32")); } /// <summary> /// If the enum type is missing, just skip emitting the attributes. /// No diagnostics. /// </summary> [Fact] public void UnsafeAttributes_MissingSecurityAction() { var text = unsafeAttributeSystemTypes + @" namespace System.Security { public class UnverifiableCodeAttribute : Attribute { } namespace Permissions { public class CodeAccessSecurityAttribute : Attribute { } public class SecurityPermissionAttribute : CodeAccessSecurityAttribute { public bool SkipVerification { get; set; } } } } "; CompileUnsafeAttributesAndCheckDiagnostics(text, false); CompileUnsafeAttributesAndCheckDiagnostics(text, true); } /// <summary> /// If the attribute constructor is missing, report a use site error. /// </summary> [Fact] public void UnsafeAttributes_MissingUnverifiableCodeAttributeCtorMissing() { var text = unsafeAttributeSystemTypes + @" namespace System.Security { public class UnverifiableCodeAttribute : Attribute { public UnverifiableCodeAttribute(object o1, object o2) { } //wrong signature, won't be found } namespace Permissions { public enum SecurityAction { RequestMinimum } public class CodeAccessSecurityAttribute : Attribute { public CodeAccessSecurityAttribute(SecurityAction action) { } } public class SecurityPermissionAttribute : CodeAccessSecurityAttribute { public SecurityPermissionAttribute(SecurityAction action) : base(action) { } public bool SkipVerification { get; set; } } } } "; CompileUnsafeAttributesAndCheckDiagnostics(text, false, // error CS0656: Missing compiler required member 'System.Security.UnverifiableCodeAttribute..ctor' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.Security.UnverifiableCodeAttribute", ".ctor"), // (22,21): error CS0518: Predefined type 'System.Int32' is not defined or imported // public enum SecurityAction Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "SecurityAction").WithArguments("System.Int32")); CompileUnsafeAttributesAndCheckDiagnostics(text, true, // error CS0656: Missing compiler required member 'System.Security.UnverifiableCodeAttribute..ctor' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.Security.UnverifiableCodeAttribute", ".ctor"), // (22,21): error CS0518: Predefined type 'System.Int32' is not defined or imported // public enum SecurityAction Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "SecurityAction").WithArguments("System.Int32")); } /// <summary> /// If the attribute constructor is missing, report a use site error. /// </summary> [Fact] public void UnsafeAttributes_SecurityPermissionAttributeCtorMissing() { var text = unsafeAttributeSystemTypes + @" namespace System.Security { public class UnverifiableCodeAttribute : Attribute { } namespace Permissions { public enum SecurityAction { RequestMinimum } public class CodeAccessSecurityAttribute : Attribute { public CodeAccessSecurityAttribute(SecurityAction action) { } } public class SecurityPermissionAttribute : CodeAccessSecurityAttribute { public SecurityPermissionAttribute(SecurityAction action, object o) //extra parameter will fail to match well-known signature : base(action) { } public bool SkipVerification { get; set; } } } } "; CompileUnsafeAttributesAndCheckDiagnostics(text, false, // error CS0656: Missing compiler required member 'System.Security.Permissions.SecurityPermissionAttribute..ctor' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.Security.Permissions.SecurityPermissionAttribute", ".ctor"), // (21,21): error CS0518: Predefined type 'System.Int32' is not defined or imported // public enum SecurityAction Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "SecurityAction").WithArguments("System.Int32")); CompileUnsafeAttributesAndCheckDiagnostics(text, true, // error CS0656: Missing compiler required member 'System.Security.Permissions.SecurityPermissionAttribute..ctor' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.Security.Permissions.SecurityPermissionAttribute", ".ctor"), // (21,21): error CS0518: Predefined type 'System.Int32' is not defined or imported // public enum SecurityAction Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "SecurityAction").WithArguments("System.Int32")); } /// <summary> /// If the attribute property is missing, report a use site error. /// </summary> [Fact] public void UnsafeAttributes_SecurityPermissionAttributePropertyMissing() { var text = unsafeAttributeSystemTypes + @" namespace System.Security { public class UnverifiableCodeAttribute : Attribute { } namespace Permissions { public enum SecurityAction { RequestMinimum } public class CodeAccessSecurityAttribute : Attribute { public CodeAccessSecurityAttribute(SecurityAction action) { } } public class SecurityPermissionAttribute : CodeAccessSecurityAttribute { public SecurityPermissionAttribute(SecurityAction action) : base(action) { } } } } "; CompileUnsafeAttributesAndCheckDiagnostics(text, false, // error CS0656: Missing compiler required member 'System.Security.Permissions.SecurityPermissionAttribute.SkipVerification' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.Security.Permissions.SecurityPermissionAttribute", "SkipVerification"), // (21,21): error CS0518: Predefined type 'System.Int32' is not defined or imported // public enum SecurityAction Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "SecurityAction").WithArguments("System.Int32")); CompileUnsafeAttributesAndCheckDiagnostics(text, true, // error CS0656: Missing compiler required member 'System.Security.Permissions.SecurityPermissionAttribute.SkipVerification' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.Security.Permissions.SecurityPermissionAttribute", "SkipVerification"), // (21,21): error CS0518: Predefined type 'System.Int32' is not defined or imported // public enum SecurityAction Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "SecurityAction").WithArguments("System.Int32")); } [WorkItem(708169, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/708169")] [Fact] public void OverloadResolutionWithUseSiteErrors() { var missingSource = @" public class Missing { } "; var libSource = @" public class Methods { public static void M1(int x) { } public static void M1(Missing x) { } public static void M2(Missing x) { } public static void M2(int x) { } } public class Indexer1 { public int this[int x] { get { return 0; } } public int this[Missing x] { get { return 0; } } } public class Indexer2 { public int this[Missing x] { get { return 0; } } public int this[int x] { get { return 0; } } } public class Constructor1 { public Constructor1(int x) { } public Constructor1(Missing x) { } } public class Constructor2 { public Constructor2(Missing x) { } public Constructor2(int x) { } } "; var testSource = @" using System; class C { static void Main() { var c1 = new Constructor1(1); var c2 = new Constructor2(2); Methods.M1(1); Methods.M2(2); Action<int> a1 = Methods.M1; Action<int> a2 = Methods.M2; var i1 = new Indexer1()[1]; var i2 = new Indexer2()[2]; } } "; var missingRef = CreateCompilation(missingSource, assemblyName: "Missing").EmitToImageReference(); var libRef = CreateCompilation(libSource, new[] { missingRef }).EmitToImageReference(); CreateCompilation(testSource, new[] { libRef /* and not missingRef */ }).VerifyDiagnostics( // (8,22): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // var c1 = new Constructor1(1); Diagnostic(ErrorCode.ERR_NoTypeDef, "Constructor1").WithArguments("Missing", "Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (9,22): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // var c2 = new Constructor2(2); Diagnostic(ErrorCode.ERR_NoTypeDef, "Constructor2").WithArguments("Missing", "Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (9,9): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // Methods.M1(1); Diagnostic(ErrorCode.ERR_NoTypeDef, "Methods.M1").WithArguments("Missing", "Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (10,9): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // Methods.M2(2); Diagnostic(ErrorCode.ERR_NoTypeDef, "Methods.M2").WithArguments("Missing", "Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (14,26): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // Action<int> a1 = Methods.M1; Diagnostic(ErrorCode.ERR_NoTypeDef, "Methods.M1").WithArguments("Missing", "Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (15,26): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // Action<int> a2 = Methods.M2; Diagnostic(ErrorCode.ERR_NoTypeDef, "Methods.M2").WithArguments("Missing", "Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (17,18): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // var i1 = new Indexer1()[1]; Diagnostic(ErrorCode.ERR_NoTypeDef, "new Indexer1()[1]").WithArguments("Missing", "Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (18,18): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // var i2 = new Indexer2()[2]; Diagnostic(ErrorCode.ERR_NoTypeDef, "new Indexer2()[2]").WithArguments("Missing", "Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); } [WorkItem(708169, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/708169")] [Fact] public void OverloadResolutionWithUseSiteErrors_LessDerived() { var missingSource = @" public class Missing { } "; var libSource = @" public class Base { public int M(int x) { return 0; } public int M(Missing x) { return 0; } public int this[int x] { get { return 0; } } public int this[Missing x] { get { return 0; } } } "; var testSource = @" class Derived : Base { static void Main() { var d = new Derived(); int i; i = d.M(1); i = d.M(""A""); i = d[1]; i = d[""A""]; } public int M(string x) { return 0; } public int this[string x] { get { return 0; } } } "; var missingRef = CreateCompilation(missingSource, assemblyName: "Missing").EmitToImageReference(); var libRef = CreateCompilation(libSource, new[] { missingRef }).EmitToImageReference(); CreateCompilation(testSource, new[] { libRef, missingRef }).VerifyDiagnostics(); // NOTE: No errors reported when the Derived member wins. CreateCompilation(testSource, new[] { libRef /* and not missingRef */ }).VerifyDiagnostics( // (9,13): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // i = d.M(1); Diagnostic(ErrorCode.ERR_NoTypeDef, "d.M").WithArguments("Missing", "Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (12,13): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // i = d[1]; Diagnostic(ErrorCode.ERR_NoTypeDef, "d[1]").WithArguments("Missing", "Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); } [WorkItem(708169, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/708169")] [Fact] public void OverloadResolutionWithUseSiteErrors_NoCorrespondingParameter() { var missingSource = @" public class Missing { } "; var libSource = @" public class C { public C(string x, int y = 1) { } public C(Missing x) { } public int M(string x, int y = 1) { return 0; } public int M(Missing x) { return 0; } public int this[string x, int y = 1] { get { return 0; } } public int this[Missing x] { get { return 0; } } } "; var testSource = @" class Test { static void Main() { C c; int i; c = new C(null, 1); // Fine c = new C(""A""); // Error i = c.M(null, 1); // Fine i = c.M(""A""); // Error i = c[null, 1]; // Fine i = c[""A""]; // Error } } "; var missingRef = CreateCompilation(missingSource, assemblyName: "Missing").EmitToImageReference(); var libRef = CreateCompilation(libSource, new[] { missingRef }).EmitToImageReference(); CreateCompilation(testSource, new[] { libRef, missingRef }).VerifyDiagnostics(); CreateCompilation(testSource, new[] { libRef /* and not missingRef */ }).VerifyDiagnostics( // (10,17): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // c = new C("A"); // Error Diagnostic(ErrorCode.ERR_NoTypeDef, "C").WithArguments("Missing", "Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (13,13): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // i = c.M("A"); // Error Diagnostic(ErrorCode.ERR_NoTypeDef, "c.M").WithArguments("Missing", "Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (16,13): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // i = c["A"]; // Error Diagnostic(ErrorCode.ERR_NoTypeDef, @"c[""A""]").WithArguments("Missing", "Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); } [WorkItem(708169, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/708169")] [Fact] public void OverloadResolutionWithUseSiteErrors_NameUsedForPositional() { var missingSource = @" public class Missing { } "; var libSource = @" public class C { public C(string x, string y) { } public C(Missing y, string x) { } public int M(string x, string y) { return 0; } public int M(Missing y, string x) { return 0; } public int this[string x, string y] { get { return 0; } } public int this[Missing y, string x] { get { return 0; } } } "; var testSource = @" class Test { static void Main() { C c; int i; c = new C(""A"", y: null); // Fine c = new C(""A"", null); // Error i = c.M(""A"", y: null); // Fine i = c.M(""A"", null); // Error i = c[""A"", y: null]; // Fine i = c[""A"", null]; // Error } } "; var missingRef = CreateCompilation(missingSource, assemblyName: "Missing").EmitToImageReference(); var libRef = CreateCompilation(libSource, new[] { missingRef }).EmitToImageReference(); CreateCompilation(testSource, new[] { libRef, missingRef }).VerifyDiagnostics(); CreateCompilation(testSource, new[] { libRef /* and not missingRef */ }).VerifyDiagnostics( // (10,17): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // c = new C("A", null); // Error Diagnostic(ErrorCode.ERR_NoTypeDef, "C").WithArguments("Missing", "Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (13,13): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // i = c.M("A", null); // Error Diagnostic(ErrorCode.ERR_NoTypeDef, "c.M").WithArguments("Missing", "Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (16,13): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // i = c["A", null]; // Error Diagnostic(ErrorCode.ERR_NoTypeDef, @"c[""A"", null]").WithArguments("Missing", "Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); } [WorkItem(708169, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/708169")] [Fact] public void OverloadResolutionWithUseSiteErrors_RequiredParameterMissing() { var missingSource = @" public class Missing { } "; var libSource = @" public class C { public C(string x, object y = null) { } public C(Missing x, string y) { } public int M(string x, object y = null) { return 0; } public int M(Missing x, string y) { return 0; } public int this[string x, object y = null] { get { return 0; } } public int this[Missing x, string y] { get { return 0; } } } "; var testSource = @" class Test { static void Main() { C c; int i; c = new C(null); // Fine c = new C(null, ""A""); // Error i = c.M(null); // Fine i = c.M(null, ""A""); // Error i = c[null]; // Fine i = c[null, ""A""]; // Error } } "; var missingRef = CreateCompilation(missingSource, assemblyName: "Missing").EmitToImageReference(); var libRef = CreateCompilation(libSource, new[] { missingRef }).EmitToImageReference(); CreateCompilation(testSource, new[] { libRef, missingRef }).VerifyDiagnostics(); CreateCompilation(testSource, new[] { libRef /* and not missingRef */ }).VerifyDiagnostics( // (10,17): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // c = new C(null, "A"); // Error Diagnostic(ErrorCode.ERR_NoTypeDef, "C").WithArguments("Missing", "Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (13,13): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // i = c.M(null, "A"); // Error Diagnostic(ErrorCode.ERR_NoTypeDef, "c.M").WithArguments("Missing", "Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (16,13): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // i = c[null, "A"]; // Error Diagnostic(ErrorCode.ERR_NoTypeDef, @"c[null, ""A""]").WithArguments("Missing", "Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); } [Fact] public void OverloadResolutionWithUseSiteErrors_WithParamsArguments_ReturnsUseSiteErrors() { var missingSource = @" public class Missing { } "; var libSource = @" public class C { public static Missing GetMissing(params int[] args) { return null; } public static void SetMissing(params Missing[] args) { } public static Missing GetMissing(string firstArgument, params int[] args) { return null; } public static void SetMissing(string firstArgument, params Missing[] args) { } } "; var testSource = @" class Test { static void Main() { C.GetMissing(); C.GetMissing(1, 1); C.SetMissing(); C.GetMissing(string.Empty); C.GetMissing(string.Empty, 1, 1); C.SetMissing(string.Empty); } } "; var missingRef = CreateCompilation(missingSource, assemblyName: "Missing").EmitToImageReference(); var libRef = CreateCompilation(libSource, new[] { missingRef }).EmitToImageReference(); CreateCompilation(testSource, new[] { libRef, missingRef }).VerifyDiagnostics(); var getMissingDiagnostic = Diagnostic(ErrorCode.ERR_NoTypeDef, @"C.GetMissing").WithArguments("Missing", "Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"); var setMissingDiagnostic = Diagnostic(ErrorCode.ERR_NoTypeDef, @"C.SetMissing").WithArguments("Missing", "Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"); CreateCompilation(testSource, new[] { libRef /* and not missingRef */ }).VerifyDiagnostics( getMissingDiagnostic, getMissingDiagnostic, setMissingDiagnostic, getMissingDiagnostic, getMissingDiagnostic, setMissingDiagnostic); } [WorkItem(708169, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/708169")] [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void OverloadResolutionWithUnsupportedMetadata_UnsupportedMetadata_SupportedExists() { var il = @" .class public auto ansi beforefieldinit Methods extends [mscorlib]System.Object { .method public hidebysig static void M(int32 x) cil managed { ret } .method public hidebysig static void M(string modreq(int16) x) cil managed { ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } // end of class Methods .class public auto ansi beforefieldinit Indexers extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('Item')} .method public hidebysig specialname instance int32 get_Item(int32 x) cil managed { ldc.i4.0 ret } .method public hidebysig specialname instance int32 get_Item(string modreq(int16) x) cil managed { ldc.i4.0 ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .property instance int32 Item(int32) { .get instance int32 Indexers::get_Item(int32) } .property instance int32 Item(string modreq(int16)) { .get instance int32 Indexers::get_Item(string modreq(int16)) } } // end of class Indexers .class public auto ansi beforefieldinit Constructors extends [mscorlib]System.Object { .method public hidebysig specialname rtspecialname instance void .ctor(int32 x) cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .method public hidebysig specialname rtspecialname instance void .ctor(string modreq(int16) x) cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } // end of class Constructors "; var source = @" using System; class C { static void Main() { var c1 = new Constructors(1); var c2 = new Constructors(null); Methods.M(1); Methods.M(null); Action<int> a1 = Methods.M; Action<string> a2 = Methods.M; var i1 = new Indexers()[1]; var i2 = new Indexers()[null]; } } "; CreateCompilationWithILAndMscorlib40(source, il).VerifyDiagnostics( // (9,35): error CS1503: Argument 1: cannot convert from '<null>' to 'int' // var c2 = new Constructors(null); Diagnostic(ErrorCode.ERR_BadArgType, "null").WithArguments("1", "<null>", "int"), // (12,19): error CS1503: Argument 1: cannot convert from '<null>' to 'int' // Methods.M(null); Diagnostic(ErrorCode.ERR_BadArgType, "null").WithArguments("1", "<null>", "int"), // (15,37): error CS0123: No overload for 'M' matches delegate 'System.Action<string>' // Action<string> a2 = Methods.M; Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "M").WithArguments("M", "System.Action<string>"), // (18,33): error CS1503: Argument 1: cannot convert from '<null>' to 'int' // var i2 = new Indexers()[null]; Diagnostic(ErrorCode.ERR_BadArgType, "null").WithArguments("1", "<null>", "int")); } [WorkItem(708169, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/708169")] [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void OverloadResolutionWithUnsupportedMetadata_UnsupportedMetadata_SupportedDoesNotExist() { var il = @" .class public auto ansi beforefieldinit Methods extends [mscorlib]System.Object { .method public hidebysig static void M(string modreq(int16) x) cil managed { ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } // end of class Methods .class public auto ansi beforefieldinit Indexers extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('Item')} .method public hidebysig specialname instance int32 get_Item(string modreq(int16) x) cil managed { ldc.i4.0 ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .property instance int32 Item(string modreq(int16)) { .get instance int32 Indexers::get_Item(string modreq(int16)) } } // end of class Indexers .class public auto ansi beforefieldinit Constructors extends [mscorlib]System.Object { .method public hidebysig specialname rtspecialname instance void .ctor(string modreq(int16) x) cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } // end of class Constructors "; var source = @" using System; class C { static void Main() { var c2 = new Constructors(null); Methods.M(null); Action<string> a2 = Methods.M; var i2 = new Indexers()[null]; } } "; CreateCompilationWithILAndMscorlib40(source, il).VerifyDiagnostics( // (8,22): error CS0570: 'Constructors.Constructors(string)' is not supported by the language // var c2 = new Constructors(null); Diagnostic(ErrorCode.ERR_BindToBogus, "Constructors").WithArguments("Constructors.Constructors(string)").WithLocation(8, 22), // (10,17): error CS0570: 'Methods.M(string)' is not supported by the language // Methods.M(null); Diagnostic(ErrorCode.ERR_BindToBogus, "M").WithArguments("Methods.M(string)").WithLocation(10, 17), // (12,29): error CS0570: 'Methods.M(string)' is not supported by the language // Action<string> a2 = Methods.M; Diagnostic(ErrorCode.ERR_BindToBogus, "Methods.M").WithArguments("Methods.M(string)").WithLocation(12, 29), // (14,18): error CS1546: Property, indexer, or event 'Indexers.this[string]' is not supported by the language; try directly calling accessor method 'Indexers.get_Item(string)' // var i2 = new Indexers()[null]; Diagnostic(ErrorCode.ERR_BindToBogusProp1, "new Indexers()[null]").WithArguments("Indexers.this[string]", "Indexers.get_Item(string)").WithLocation(14, 18)); } [WorkItem(939928, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/939928")] [WorkItem(132, "CodePlex")] [Fact] public void MissingBaseTypeForCatch() { var source1 = @" using System; public class GeneralException : Exception {}"; CSharpCompilation comp1 = CreateCompilation(source1, assemblyName: "Base"); var source2 = @" public class SpecificException : GeneralException {}"; CSharpCompilation comp2 = CreateCompilation(source2, new MetadataReference[] { new CSharpCompilationReference(comp1) }); var source3 = @" class Test { static void Main(string[] args) { try { SpecificException e = null; throw e; } catch (SpecificException) { } } }"; CSharpCompilation comp3 = CreateCompilation(source3, new MetadataReference[] { new CSharpCompilationReference(comp2) }); DiagnosticDescription[] expected = { // (9,23): error CS0012: The type 'GeneralException' is defined in an assembly that is not referenced. You must add a reference to assembly 'Base, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // throw e; Diagnostic(ErrorCode.ERR_NoTypeDef, "e").WithArguments("GeneralException", "Base, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(9, 23), // (9,23): error CS0029: Cannot implicitly convert type 'SpecificException' to 'System.Exception' // throw e; Diagnostic(ErrorCode.ERR_NoImplicitConv, "e").WithArguments("SpecificException", "System.Exception").WithLocation(9, 23), // (11,20): error CS0155: The type caught or thrown must be derived from System.Exception // catch (SpecificException) Diagnostic(ErrorCode.ERR_BadExceptionType, "SpecificException").WithLocation(11, 20), // (11,20): error CS0012: The type 'GeneralException' is defined in an assembly that is not referenced. You must add a reference to assembly 'Base, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // catch (SpecificException) Diagnostic(ErrorCode.ERR_NoTypeDef, "SpecificException").WithArguments("GeneralException", "Base, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(11, 20) }; comp3.VerifyDiagnostics(expected); comp3 = CreateCompilation(source3, new MetadataReference[] { comp2.EmitToImageReference() }); comp3.VerifyDiagnostics(expected); } /// <summary> /// Trivial definitions of special types that will be required for testing use site errors in /// the attributes emitted for unsafe assemblies. /// </summary> private const string unsafeAttributeSystemTypes = @" namespace System { public class Object { } public class ValueType { } public class Enum { } // Diagnostic if this extends ValueType public struct Boolean { } public struct Void { } public class Attribute { } } "; /// <summary> /// Compile without corlib, and then verify semantic diagnostics, emit-metadata diagnostics, and emit diagnostics. /// </summary> private static void CompileUnsafeAttributesAndCheckDiagnostics(string corLibText, bool moduleOnly, params DiagnosticDescription[] expectedDiagnostics) { CSharpCompilationOptions options = TestOptions.UnsafeReleaseDll; if (moduleOnly) { options = options.WithOutputKind(OutputKind.NetModule); } var compilation = CreateEmptyCompilation( new[] { Parse(corLibText) }, options: options); compilation.VerifyDiagnostics(expectedDiagnostics); } #endregion Attributes for unsafe code /// <summary> /// First, compile the provided source with all assemblies and confirm that there are no errors. /// Then, compile the provided source again without the unavailable assembly and return the result. /// </summary> private static CSharpCompilation CompileWithMissingReference(string source) { var unavailableAssemblyReference = TestReferences.SymbolsTests.UseSiteErrors.Unavailable; var csharpAssemblyReference = TestReferences.SymbolsTests.UseSiteErrors.CSharp; var ilAssemblyReference = TestReferences.SymbolsTests.UseSiteErrors.IL; var successfulCompilation = CreateCompilation(source, new MetadataReference[] { unavailableAssemblyReference, csharpAssemblyReference, ilAssemblyReference }); successfulCompilation.VerifyDiagnostics(); // No diagnostics when reference is present var failingCompilation = CreateCompilation(source, new MetadataReference[] { csharpAssemblyReference, ilAssemblyReference }); return failingCompilation; } [Fact] [WorkItem(14267, "https://github.com/dotnet/roslyn/issues/14267")] public void MissingTypeKindBasisTypes() { var source1 = @" public struct A {} public enum B {} public class C {} public delegate void D(); public interface I1 {} "; var compilation1 = CreateEmptyCompilation(source1, options: TestOptions.ReleaseDll, references: new[] { MinCorlibRef }); compilation1.VerifyEmitDiagnostics(); Assert.Equal(TypeKind.Struct, compilation1.GetTypeByMetadataName("A").TypeKind); Assert.Equal(TypeKind.Enum, compilation1.GetTypeByMetadataName("B").TypeKind); Assert.Equal(TypeKind.Class, compilation1.GetTypeByMetadataName("C").TypeKind); Assert.Equal(TypeKind.Delegate, compilation1.GetTypeByMetadataName("D").TypeKind); Assert.Equal(TypeKind.Interface, compilation1.GetTypeByMetadataName("I1").TypeKind); var source2 = @" interface I2 { I1 M(A a, B b, C c, D d); } "; var compilation2 = CreateEmptyCompilation(source2, options: TestOptions.ReleaseDll, references: new[] { compilation1.EmitToImageReference(), MinCorlibRef }); compilation2.VerifyEmitDiagnostics(); CompileAndVerify(compilation2); Assert.Equal(TypeKind.Struct, compilation2.GetTypeByMetadataName("A").TypeKind); Assert.Equal(TypeKind.Enum, compilation2.GetTypeByMetadataName("B").TypeKind); Assert.Equal(TypeKind.Class, compilation2.GetTypeByMetadataName("C").TypeKind); Assert.Equal(TypeKind.Delegate, compilation2.GetTypeByMetadataName("D").TypeKind); Assert.Equal(TypeKind.Interface, compilation2.GetTypeByMetadataName("I1").TypeKind); var compilation3 = CreateEmptyCompilation(source2, options: TestOptions.ReleaseDll, references: new[] { compilation1.ToMetadataReference(), MinCorlibRef }); compilation3.VerifyEmitDiagnostics(); CompileAndVerify(compilation3); Assert.Equal(TypeKind.Struct, compilation3.GetTypeByMetadataName("A").TypeKind); Assert.Equal(TypeKind.Enum, compilation3.GetTypeByMetadataName("B").TypeKind); Assert.Equal(TypeKind.Class, compilation3.GetTypeByMetadataName("C").TypeKind); Assert.Equal(TypeKind.Delegate, compilation3.GetTypeByMetadataName("D").TypeKind); Assert.Equal(TypeKind.Interface, compilation3.GetTypeByMetadataName("I1").TypeKind); var compilation4 = CreateEmptyCompilation(source2, options: TestOptions.ReleaseDll, references: new[] { compilation1.EmitToImageReference() }); compilation4.VerifyDiagnostics( // (4,10): error CS0012: The type 'ValueType' is defined in an assembly that is not referenced. You must add a reference to assembly 'mincorlib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2'. // I1 M(A a, B b, C c, D d); Diagnostic(ErrorCode.ERR_NoTypeDef, "A").WithArguments("System.ValueType", "mincorlib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2").WithLocation(4, 10), // (4,15): error CS0012: The type 'Enum' is defined in an assembly that is not referenced. You must add a reference to assembly 'mincorlib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2'. // I1 M(A a, B b, C c, D d); Diagnostic(ErrorCode.ERR_NoTypeDef, "B").WithArguments("System.Enum", "mincorlib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2").WithLocation(4, 15), // (4,25): error CS0012: The type 'MulticastDelegate' is defined in an assembly that is not referenced. You must add a reference to assembly 'mincorlib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2'. // I1 M(A a, B b, C c, D d); Diagnostic(ErrorCode.ERR_NoTypeDef, "D").WithArguments("System.MulticastDelegate", "mincorlib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2").WithLocation(4, 25) ); var a = compilation4.GetTypeByMetadataName("A"); var b = compilation4.GetTypeByMetadataName("B"); var c = compilation4.GetTypeByMetadataName("C"); var d = compilation4.GetTypeByMetadataName("D"); var i1 = compilation4.GetTypeByMetadataName("I1"); Assert.Equal(TypeKind.Class, a.TypeKind); Assert.NotNull(a.GetUseSiteDiagnostic()); Assert.Equal(TypeKind.Class, b.TypeKind); Assert.NotNull(b.GetUseSiteDiagnostic()); Assert.Equal(TypeKind.Class, c.TypeKind); Assert.Null(c.GetUseSiteDiagnostic()); Assert.Equal(TypeKind.Class, d.TypeKind); Assert.NotNull(d.GetUseSiteDiagnostic()); Assert.Equal(TypeKind.Interface, i1.TypeKind); Assert.Null(i1.GetUseSiteDiagnostic()); var compilation5 = CreateEmptyCompilation(source2, options: TestOptions.ReleaseDll, references: new[] { compilation1.ToMetadataReference() }); compilation5.VerifyEmitDiagnostics( // warning CS8021: No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options. Diagnostic(ErrorCode.WRN_NoRuntimeMetadataVersion).WithLocation(1, 1) ); CompileAndVerify(compilation5); Assert.Equal(TypeKind.Struct, compilation5.GetTypeByMetadataName("A").TypeKind); Assert.Equal(TypeKind.Enum, compilation5.GetTypeByMetadataName("B").TypeKind); Assert.Equal(TypeKind.Class, compilation5.GetTypeByMetadataName("C").TypeKind); Assert.Equal(TypeKind.Delegate, compilation5.GetTypeByMetadataName("D").TypeKind); Assert.Equal(TypeKind.Interface, compilation5.GetTypeByMetadataName("I1").TypeKind); var compilation6 = CreateEmptyCompilation(source2, options: TestOptions.ReleaseDll, references: new[] { compilation1.EmitToImageReference(), MscorlibRef }); compilation6.VerifyDiagnostics( // (4,10): error CS0012: The type 'ValueType' is defined in an assembly that is not referenced. You must add a reference to assembly 'mincorlib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2'. // I1 M(A a, B b, C c, D d); Diagnostic(ErrorCode.ERR_NoTypeDef, "A").WithArguments("System.ValueType", "mincorlib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2").WithLocation(4, 10), // (4,15): error CS0012: The type 'Enum' is defined in an assembly that is not referenced. You must add a reference to assembly 'mincorlib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2'. // I1 M(A a, B b, C c, D d); Diagnostic(ErrorCode.ERR_NoTypeDef, "B").WithArguments("System.Enum", "mincorlib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2").WithLocation(4, 15), // (4,25): error CS0012: The type 'MulticastDelegate' is defined in an assembly that is not referenced. You must add a reference to assembly 'mincorlib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2'. // I1 M(A a, B b, C c, D d); Diagnostic(ErrorCode.ERR_NoTypeDef, "D").WithArguments("System.MulticastDelegate", "mincorlib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2").WithLocation(4, 25) ); a = compilation6.GetTypeByMetadataName("A"); b = compilation6.GetTypeByMetadataName("B"); c = compilation6.GetTypeByMetadataName("C"); d = compilation6.GetTypeByMetadataName("D"); i1 = compilation6.GetTypeByMetadataName("I1"); Assert.Equal(TypeKind.Class, a.TypeKind); Assert.NotNull(a.GetUseSiteDiagnostic()); Assert.Equal(TypeKind.Class, b.TypeKind); Assert.NotNull(b.GetUseSiteDiagnostic()); Assert.Equal(TypeKind.Class, c.TypeKind); Assert.Null(c.GetUseSiteDiagnostic()); Assert.Equal(TypeKind.Class, d.TypeKind); Assert.NotNull(d.GetUseSiteDiagnostic()); Assert.Equal(TypeKind.Interface, i1.TypeKind); Assert.Null(i1.GetUseSiteDiagnostic()); var compilation7 = CreateEmptyCompilation(source2, options: TestOptions.ReleaseDll, references: new[] { compilation1.ToMetadataReference(), MscorlibRef }); compilation7.VerifyEmitDiagnostics(); CompileAndVerify(compilation7); Assert.Equal(TypeKind.Struct, compilation7.GetTypeByMetadataName("A").TypeKind); Assert.Equal(TypeKind.Enum, compilation7.GetTypeByMetadataName("B").TypeKind); Assert.Equal(TypeKind.Class, compilation7.GetTypeByMetadataName("C").TypeKind); Assert.Equal(TypeKind.Delegate, compilation7.GetTypeByMetadataName("D").TypeKind); Assert.Equal(TypeKind.Interface, compilation7.GetTypeByMetadataName("I1").TypeKind); } [Fact, WorkItem(15435, "https://github.com/dotnet/roslyn/issues/15435")] public void TestGettingAssemblyIdsFromDiagnostic1() { var text = @" class C : CSharpErrors.ClassMethods { public override UnavailableClass ReturnType1() { return null; } public override UnavailableClass[] ReturnType2() { return null; } }"; var compilation = CompileWithMissingReference(text); var diagnostics = compilation.GetDiagnostics(); Assert.True(diagnostics.Any(d => d.Code == (int)ErrorCode.ERR_NoTypeDef)); foreach (var diagnostic in diagnostics) { if (diagnostic.Code == (int)ErrorCode.ERR_NoTypeDef) { var actualAssemblyId = compilation.GetUnreferencedAssemblyIdentities(diagnostic).Single(); AssemblyIdentity expectedAssemblyId; AssemblyIdentity.TryParseDisplayName("Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", out expectedAssemblyId); Assert.Equal(actualAssemblyId, expectedAssemblyId); } } } private static readonly MetadataReference UnmanagedUseSiteError_Ref1 = CreateCompilation(@" public struct S1 { public int i; }", assemblyName: "libS1").ToMetadataReference(); private static readonly MetadataReference UnmanagedUseSiteError_Ref2 = CreateCompilation(@" public struct S2 { public S1 s1; } ", references: new[] { UnmanagedUseSiteError_Ref1 }, assemblyName: "libS2").ToMetadataReference(); [Fact] public void Unmanaged_UseSiteError_01() { var source = @" class C { unsafe void M(S2 s2) { var ptr = &s2; } } "; var comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll, references: new[] { UnmanagedUseSiteError_Ref2 }); comp.VerifyEmitDiagnostics( // (6,19): error CS0012: The type 'S1' is defined in an assembly that is not referenced. You must add a reference to assembly 'libS1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // var ptr = &s2; Diagnostic(ErrorCode.ERR_NoTypeDef, "&s2").WithArguments("S1", "libS1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 19), // (6,19): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('S2') // var ptr = &s2; Diagnostic(ErrorCode.ERR_ManagedAddr, "&s2").WithArguments("S2").WithLocation(6, 19) ); comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll, references: new[] { UnmanagedUseSiteError_Ref1, UnmanagedUseSiteError_Ref2 }); comp.VerifyEmitDiagnostics(); } [Fact] public void Unmanaged_UseSiteError_02() { var source = @" class C { unsafe void M() { var size = sizeof(S2); } } "; var comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll, references: new[] { UnmanagedUseSiteError_Ref2 }); comp.VerifyEmitDiagnostics( // (6,20): error CS0012: The type 'S1' is defined in an assembly that is not referenced. You must add a reference to assembly 'libS1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // var size = sizeof(S2); Diagnostic(ErrorCode.ERR_NoTypeDef, "sizeof(S2)").WithArguments("S1", "libS1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 20), // (6,20): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('S2') // var size = sizeof(S2); Diagnostic(ErrorCode.ERR_ManagedAddr, "sizeof(S2)").WithArguments("S2").WithLocation(6, 20)); comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll, references: new[] { UnmanagedUseSiteError_Ref1, UnmanagedUseSiteError_Ref2 }); comp.VerifyEmitDiagnostics(); } [Fact] public void Unmanaged_UseSiteError_03() { var source = @" class C { unsafe void M(S2* ptr) { } } "; var comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll, references: new[] { UnmanagedUseSiteError_Ref2 }); comp.VerifyEmitDiagnostics( // (4,23): error CS0012: The type 'S1' is defined in an assembly that is not referenced. You must add a reference to assembly 'libS1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // unsafe void M(S2* ptr) Diagnostic(ErrorCode.ERR_NoTypeDef, "ptr").WithArguments("S1", "libS1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(4, 23), // (4,23): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('S2') // unsafe void M(S2* ptr) Diagnostic(ErrorCode.ERR_ManagedAddr, "ptr").WithArguments("S2").WithLocation(4, 23)); comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll, references: new[] { UnmanagedUseSiteError_Ref1, UnmanagedUseSiteError_Ref2 }); comp.VerifyEmitDiagnostics(); } [Fact] public void Unmanaged_UseSiteError_04() { var source = @" class C { unsafe void M() { S2* span = stackalloc S2[16]; S2* span2 = stackalloc [] { default(S2) }; } } "; var comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll, references: new[] { UnmanagedUseSiteError_Ref2 }); comp.VerifyEmitDiagnostics( // (6,9): error CS0012: The type 'S1' is defined in an assembly that is not referenced. You must add a reference to assembly 'libS1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // S2* span = stackalloc S2[16]; Diagnostic(ErrorCode.ERR_NoTypeDef, "S2*").WithArguments("S1", "libS1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 9), // (6,9): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('S2') // S2* span = stackalloc S2[16]; Diagnostic(ErrorCode.ERR_ManagedAddr, "S2*").WithArguments("S2").WithLocation(6, 9), // (6,31): error CS0012: The type 'S1' is defined in an assembly that is not referenced. You must add a reference to assembly 'libS1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // S2* span = stackalloc S2[16]; Diagnostic(ErrorCode.ERR_NoTypeDef, "S2").WithArguments("S1", "libS1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 31), // (6,31): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('S2') // S2* span = stackalloc S2[16]; Diagnostic(ErrorCode.ERR_ManagedAddr, "S2").WithArguments("S2").WithLocation(6, 31), // (7,9): error CS0012: The type 'S1' is defined in an assembly that is not referenced. You must add a reference to assembly 'libS1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // S2* span2 = stackalloc [] { default(S2) }; Diagnostic(ErrorCode.ERR_NoTypeDef, "S2*").WithArguments("S1", "libS1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 9), // (7,9): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('S2') // S2* span2 = stackalloc [] { default(S2) }; Diagnostic(ErrorCode.ERR_ManagedAddr, "S2*").WithArguments("S2").WithLocation(7, 9), // (7,21): error CS0012: The type 'S1' is defined in an assembly that is not referenced. You must add a reference to assembly 'libS1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // S2* span2 = stackalloc [] { default(S2) }; Diagnostic(ErrorCode.ERR_NoTypeDef, "stackalloc [] { default(S2) }").WithArguments("S1", "libS1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 21), // (7,21): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('S2') // S2* span2 = stackalloc [] { default(S2) }; Diagnostic(ErrorCode.ERR_ManagedAddr, "stackalloc [] { default(S2) }").WithArguments("S2").WithLocation(7, 21)); comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll, references: new[] { UnmanagedUseSiteError_Ref1, UnmanagedUseSiteError_Ref2 }); comp.VerifyEmitDiagnostics(); } [Fact] public void Unmanaged_UseSiteError_05() { var source = @" class C { S2 s2; unsafe void M() { fixed (S2* ptr = &s2) { } } } "; var comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll, references: new[] { UnmanagedUseSiteError_Ref2 }); comp.VerifyEmitDiagnostics( // (7,16): error CS0012: The type 'S1' is defined in an assembly that is not referenced. You must add a reference to assembly 'libS1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // fixed (S2* ptr = &s2) Diagnostic(ErrorCode.ERR_NoTypeDef, "S2*").WithArguments("S1", "libS1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 16), // (7,16): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('S2') // fixed (S2* ptr = &s2) Diagnostic(ErrorCode.ERR_ManagedAddr, "S2*").WithArguments("S2").WithLocation(7, 16), // (7,26): error CS0012: The type 'S1' is defined in an assembly that is not referenced. You must add a reference to assembly 'libS1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // fixed (S2* ptr = &s2) Diagnostic(ErrorCode.ERR_NoTypeDef, "&s2").WithArguments("S1", "libS1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 26), // (7,26): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('S2') // fixed (S2* ptr = &s2) Diagnostic(ErrorCode.ERR_ManagedAddr, "&s2").WithArguments("S2").WithLocation(7, 26) ); comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll, references: new[] { UnmanagedUseSiteError_Ref1, UnmanagedUseSiteError_Ref2 }); comp.VerifyEmitDiagnostics(); } [Fact] public void Unmanaged_UseSiteError_06() { var source = @" class C { void M<T>(T t) where T : unmanaged { } void M1() { M(default(S2)); // 1, 2 M(default(S2)); // 3, 4 } } "; var comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll, references: new[] { UnmanagedUseSiteError_Ref2 }); comp.VerifyEmitDiagnostics( // (8,9): error CS8377: The type 'S2' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'C.M<T>(T)' // M(default(S2)); // 1, 2 Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M").WithArguments("C.M<T>(T)", "T", "S2").WithLocation(8, 9), // (8,9): error CS0012: The type 'S1' is defined in an assembly that is not referenced. You must add a reference to assembly 'libS1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // M(default(S2)); // 1, 2 Diagnostic(ErrorCode.ERR_NoTypeDef, "M").WithArguments("S1", "libS1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(8, 9), // (9,9): error CS8377: The type 'S2' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'C.M<T>(T)' // M(default(S2)); // 3, 4 Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M").WithArguments("C.M<T>(T)", "T", "S2").WithLocation(9, 9), // (9,9): error CS0012: The type 'S1' is defined in an assembly that is not referenced. You must add a reference to assembly 'libS1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // M(default(S2)); // 3, 4 Diagnostic(ErrorCode.ERR_NoTypeDef, "M").WithArguments("S1", "libS1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(9, 9)); comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll, references: new[] { UnmanagedUseSiteError_Ref1, UnmanagedUseSiteError_Ref2 }); comp.VerifyEmitDiagnostics(); } [Fact] public void Unmanaged_UseSiteError_07() { var source = @" public struct S3 { public S2 s2; } class C { void M<T>(T t) where T : unmanaged { } void M1() { M(default(S3)); // 1, 2 M(default(S3)); // 3, 4 } } "; var comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll, references: new[] { UnmanagedUseSiteError_Ref2 }); comp.VerifyEmitDiagnostics( // (13,9): error CS8377: The type 'S3' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'C.M<T>(T)' // M(default(S3)); // 1, 2 Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M").WithArguments("C.M<T>(T)", "T", "S3").WithLocation(13, 9), // (13,9): error CS0012: The type 'S1' is defined in an assembly that is not referenced. You must add a reference to assembly 'libS1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // M(default(S3)); // 1, 2 Diagnostic(ErrorCode.ERR_NoTypeDef, "M").WithArguments("S1", "libS1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(13, 9), // (14,9): error CS8377: The type 'S3' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'C.M<T>(T)' // M(default(S3)); // 3, 4 Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M").WithArguments("C.M<T>(T)", "T", "S3").WithLocation(14, 9), // (14,9): error CS0012: The type 'S1' is defined in an assembly that is not referenced. You must add a reference to assembly 'libS1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // M(default(S3)); // 3, 4 Diagnostic(ErrorCode.ERR_NoTypeDef, "M").WithArguments("S1", "libS1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(14, 9)); comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll, references: new[] { UnmanagedUseSiteError_Ref1, UnmanagedUseSiteError_Ref2 }); comp.VerifyEmitDiagnostics(); } [Fact] public void Unmanaged_UseSiteError_08() { var source = @" using System.Threading.Tasks; using System; class C { async Task M1() { S2 s2 = M2(); await M1(); Console.Write(s2); } S2 M2() => default; } "; var comp = CreateCompilation(source, references: new[] { UnmanagedUseSiteError_Ref2 }); comp.VerifyEmitDiagnostics( // error CS0012: The type 'S1' is defined in an assembly that is not referenced. You must add a reference to assembly 'libS1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Diagnostic(ErrorCode.ERR_NoTypeDef).WithArguments("S1", "libS1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(1, 1), // error CS0012: The type 'S1' is defined in an assembly that is not referenced. You must add a reference to assembly 'libS1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Diagnostic(ErrorCode.ERR_NoTypeDef).WithArguments("S1", "libS1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(1, 1)); comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll, references: new[] { UnmanagedUseSiteError_Ref1, UnmanagedUseSiteError_Ref2 }); comp.VerifyEmitDiagnostics(); } [Fact] public void Unmanaged_UseSiteError_09() { var source = @" public struct S3 { public S2 s2; } "; var comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll, references: new[] { UnmanagedUseSiteError_Ref2 }); comp.VerifyEmitDiagnostics(); var s3 = comp.GetMember<NamedTypeSymbol>("S3"); verifyIsManagedType(); verifyIsManagedType(); void verifyIsManagedType() { var managedKindUseSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(s3.ContainingAssembly); Assert.True(s3.IsManagedType(ref managedKindUseSiteInfo)); managedKindUseSiteInfo.Diagnostics.Verify( // error CS0012: The type 'S1' is defined in an assembly that is not referenced. You must add a reference to assembly 'libS1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Diagnostic(ErrorCode.ERR_NoTypeDef).WithArguments("S1", "libS1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(1, 1) ); } comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll, references: new[] { UnmanagedUseSiteError_Ref1, UnmanagedUseSiteError_Ref2 }); comp.VerifyEmitDiagnostics(); s3 = comp.GetMember<NamedTypeSymbol>("S3"); verifyIsUnmanagedType(); verifyIsUnmanagedType(); void verifyIsUnmanagedType() { var managedKindUseSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(s3.ContainingAssembly); Assert.False(s3.IsManagedType(ref managedKindUseSiteInfo)); Assert.Null(managedKindUseSiteInfo.Diagnostics); } } [Fact] public void OverrideWithModreq_01() { var il = @" .class public auto ansi beforefieldinit CL1 extends[mscorlib] System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call instance void[mscorlib] System.Object::.ctor() IL_0006: ret } .method public hidebysig newslot virtual instance int32 modreq([mscorlib]System.Runtime.CompilerServices.IsConst) get_P() cil managed { .maxstack 8 ldc.i4.s 123 ret } } // end of class CL1 "; var source = @" class Test : CL1 { public override int get_P() { return default; } } "; CreateCompilationWithIL(source, il).VerifyDiagnostics( // (4,25): error CS0570: 'CL1.get_P()' is not supported by the language // public override int get_P() Diagnostic(ErrorCode.ERR_BindToBogus, "get_P").WithArguments("CL1.get_P()").WithLocation(4, 25) ); } [Fact] public void OverrideWithModreq_02() { var il = @" .class public auto ansi beforefieldinit CL1 extends[mscorlib] System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call instance void[mscorlib] System.Object::.ctor() IL_0006: ret } .method public hidebysig newslot virtual instance int32 modreq([mscorlib]System.Runtime.CompilerServices.IsConst) get_P() cil managed { .maxstack 8 ldc.i4.s 123 ret } .property instance int32 modreq([mscorlib]System.Runtime.CompilerServices.IsConst) P() { .get instance int32 modreq([mscorlib]System.Runtime.CompilerServices.IsConst) CL1::get_P() } } // end of class CL1 "; var source = @" class Test : CL1 { public override int P { get => throw null; } } "; CreateCompilationWithIL(source, il).VerifyDiagnostics( // (4,25): error CS0569: 'Test.P': cannot override 'CL1.P' because it is not supported by the language // public override int P Diagnostic(ErrorCode.ERR_CantOverrideBogusMethod, "P").WithArguments("Test.P", "CL1.P").WithLocation(4, 25) ); } [Fact] public void OverrideWithModreq_03() { var il = @" .class public auto ansi beforefieldinit CL1 extends[mscorlib] System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call instance void[mscorlib] System.Object::.ctor() IL_0006: ret } .method public hidebysig newslot virtual instance int32 modreq([mscorlib]System.Runtime.CompilerServices.IsConst) get_P() cil managed { .maxstack 8 ldc.i4.s 123 ret } .property instance int32 P() { .get instance int32 modreq([mscorlib]System.Runtime.CompilerServices.IsConst) CL1::get_P() } } // end of class CL1 "; var source = @" class Test : CL1 { public override int P { get => throw null; } } "; CreateCompilationWithIL(source, il).VerifyDiagnostics( // (6,9): error CS0570: 'CL1.P.get' is not supported by the language // get => throw null; Diagnostic(ErrorCode.ERR_BindToBogus, "get").WithArguments("CL1.P.get").WithLocation(6, 9) ); } [Fact] public void OverrideWithModreq_04() { var il = @" .class public auto ansi beforefieldinit CL1 extends[mscorlib] System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call instance void[mscorlib] System.Object::.ctor() IL_0006: ret } .method public hidebysig newslot virtual instance void modreq([mscorlib]System.Runtime.CompilerServices.IsConst) set_P(int32 x) cil managed { .maxstack 8 ret } .property instance int32 P() { .set instance void modreq([mscorlib]System.Runtime.CompilerServices.IsConst) CL1::set_P(int32) } } // end of class CL1 "; var source = @" class Test : CL1 { public override int P { set => throw null; } } "; CreateCompilationWithIL(source, il).VerifyDiagnostics( // (6,9): error CS0570: 'CL1.P.set' is not supported by the language // set => throw null; Diagnostic(ErrorCode.ERR_BindToBogus, "set").WithArguments("CL1.P.set").WithLocation(6, 9) ); } [Fact] public void OverrideWithModreq_05() { var il = @" .class public auto ansi beforefieldinit CL1 extends[mscorlib] System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call instance void[mscorlib] System.Object::.ctor() IL_0006: ret } .method public hidebysig newslot virtual instance int32 modreq([mscorlib]System.Runtime.CompilerServices.IsConst) get_P() cil managed { .maxstack 8 ldc.i4.s 123 ret } .method public hidebysig newslot virtual instance void modreq([mscorlib]System.Runtime.CompilerServices.IsConst) set_P(int32 x) cil managed { .maxstack 8 ret } .property instance int32 P() { .get instance int32 modreq([mscorlib]System.Runtime.CompilerServices.IsConst) CL1::get_P() .set instance void modreq([mscorlib]System.Runtime.CompilerServices.IsConst) CL1::set_P(int32) } } // end of class CL1 "; var source = @" class Test : CL1 { public override int P { get => throw null; set => throw null; } } "; CreateCompilationWithIL(source, il).VerifyDiagnostics( // (6,9): error CS0570: 'CL1.P.get' is not supported by the language // get => throw null; Diagnostic(ErrorCode.ERR_BindToBogus, "get").WithArguments("CL1.P.get").WithLocation(6, 9), // (7,9): error CS0570: 'CL1.P.set' is not supported by the language // set => throw null; Diagnostic(ErrorCode.ERR_BindToBogus, "set").WithArguments("CL1.P.set").WithLocation(7, 9) ); } [Fact] public void OverrideWithModreq_06() { var il = @" .class public auto ansi beforefieldinit CL1 extends[mscorlib] System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call instance void[mscorlib] System.Object::.ctor() IL_0006: ret } .method public hidebysig newslot virtual instance int32 get_P() cil managed { .maxstack 8 ldc.i4.s 123 ret } .method public hidebysig newslot virtual instance void modreq([mscorlib]System.Runtime.CompilerServices.IsConst) set_P(int32 x) cil managed { .maxstack 8 ret } .property instance int32 P() { .get instance int32 CL1::get_P() .set instance void modreq([mscorlib]System.Runtime.CompilerServices.IsConst) CL1::set_P(int32) } } // end of class CL1 "; var source = @" class Test : CL1 { public override int P { get => throw null; set => throw null; } } "; CreateCompilationWithIL(source, il).VerifyDiagnostics( // (7,9): error CS0570: 'CL1.P.set' is not supported by the language // set => throw null; Diagnostic(ErrorCode.ERR_BindToBogus, "set").WithArguments("CL1.P.set").WithLocation(7, 9) ); } [Fact] public void OverrideWithModreq_07() { var il = @" .class public auto ansi beforefieldinit CL1 extends[mscorlib] System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call instance void[mscorlib] System.Object::.ctor() IL_0006: ret } .method public hidebysig newslot virtual instance int32 modreq([mscorlib]System.Runtime.CompilerServices.IsConst) get_P() cil managed { .maxstack 8 ldc.i4.s 123 ret } .method public hidebysig newslot virtual instance void set_P(int32 x) cil managed { .maxstack 8 ret } .property instance int32 P() { .get instance int32 modreq([mscorlib]System.Runtime.CompilerServices.IsConst) CL1::get_P() .set instance void CL1::set_P(int32) } } // end of class CL1 "; var source = @" class Test : CL1 { public override int P { get => throw null; set => throw null; } } "; CreateCompilationWithIL(source, il).VerifyDiagnostics( // (6,9): error CS0570: 'CL1.P.get' is not supported by the language // get => throw null; Diagnostic(ErrorCode.ERR_BindToBogus, "get").WithArguments("CL1.P.get").WithLocation(6, 9) ); } [Fact] public void OverrideWithModreq_08() { var il = @" .class public auto ansi beforefieldinit CL1 extends[mscorlib] System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call instance void[mscorlib] System.Object::.ctor() IL_0006: ret } .method public hidebysig specialname newslot virtual instance void add_E ( class [mscorlib]System.Action modreq([mscorlib]System.Runtime.CompilerServices.IsConst) 'value' ) cil managed { ret } .method public hidebysig specialname newslot virtual instance void remove_E ( class [mscorlib]System.Action modreq([mscorlib]System.Runtime.CompilerServices.IsConst) 'value' ) cil managed { ret } .event [mscorlib]System.Action E { .addon instance void CL1::add_E(class [mscorlib]System.Action modreq([mscorlib]System.Runtime.CompilerServices.IsConst)) .removeon instance void CL1::remove_E(class [mscorlib]System.Action modreq([mscorlib]System.Runtime.CompilerServices.IsConst)) } } // end of class CL1 "; var source = @" class Test : CL1 { public override event System.Action E { add => throw null; remove => throw null; } } "; CreateCompilationWithIL(source, il).VerifyDiagnostics( // (6,9): error CS0570: 'CL1.E.add' is not supported by the language // add => throw null; Diagnostic(ErrorCode.ERR_BindToBogus, "add").WithArguments("CL1.E.add").WithLocation(6, 9), // (7,9): error CS0570: 'CL1.E.remove' is not supported by the language // remove => throw null; Diagnostic(ErrorCode.ERR_BindToBogus, "remove").WithArguments("CL1.E.remove").WithLocation(7, 9) ); } [Fact] public void OverrideWithModreq_09() { var il = @" .class public auto ansi beforefieldinit CL1 extends[mscorlib] System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call instance void[mscorlib] System.Object::.ctor() IL_0006: ret } .method public hidebysig specialname newslot virtual instance void add_E ( class [mscorlib]System.Action 'value' ) cil managed { ret } .method public hidebysig specialname newslot virtual instance void remove_E ( class [mscorlib]System.Action modreq([mscorlib]System.Runtime.CompilerServices.IsConst) 'value' ) cil managed { ret } .event [mscorlib]System.Action E { .addon instance void CL1::add_E(class [mscorlib]System.Action) .removeon instance void CL1::remove_E(class [mscorlib]System.Action modreq([mscorlib]System.Runtime.CompilerServices.IsConst)) } } // end of class CL1 "; var source = @" class Test : CL1 { public override event System.Action E { add => throw null; remove => throw null; } } "; CreateCompilationWithIL(source, il).VerifyDiagnostics( // (7,9): error CS0570: 'CL1.E.remove' is not supported by the language // remove => throw null; Diagnostic(ErrorCode.ERR_BindToBogus, "remove").WithArguments("CL1.E.remove").WithLocation(7, 9) ); } [Fact] public void OverrideWithModreq_10() { var il = @" .class public auto ansi beforefieldinit CL1 extends[mscorlib] System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call instance void[mscorlib] System.Object::.ctor() IL_0006: ret } .method public hidebysig specialname newslot virtual instance void add_E ( class [mscorlib]System.Action modreq([mscorlib]System.Runtime.CompilerServices.IsConst) 'value' ) cil managed { ret } .method public hidebysig specialname newslot virtual instance void remove_E ( class [mscorlib]System.Action 'value' ) cil managed { ret } .event [mscorlib]System.Action E { .addon instance void CL1::add_E(class [mscorlib]System.Action modreq([mscorlib]System.Runtime.CompilerServices.IsConst)) .removeon instance void CL1::remove_E(class [mscorlib]System.Action) } } // end of class CL1 "; var source = @" class Test : CL1 { public override event System.Action E { add => throw null; remove => throw null; } } "; CreateCompilationWithIL(source, il).VerifyDiagnostics( // (6,9): error CS0570: 'CL1.E.add' is not supported by the language // add => throw null; Diagnostic(ErrorCode.ERR_BindToBogus, "add").WithArguments("CL1.E.add").WithLocation(6, 9) ); } [Fact] public void ImplementWithModreq_01() { var il = @" .class interface public abstract auto ansi CL1 { .method public hidebysig newslot specialname abstract virtual instance int32 modreq([mscorlib]System.Runtime.CompilerServices.IsConst) get_P() cil managed { } } // end of class CL1 "; var source = @" class Test : CL1 { public int get_P() { return default; } } "; CreateCompilationWithIL(source, il).VerifyDiagnostics( // (4,16): error CS0570: 'CL1.get_P()' is not supported by the language // public int get_P() Diagnostic(ErrorCode.ERR_BindToBogus, "get_P").WithArguments("CL1.get_P()").WithLocation(4, 16) ); } [Fact] public void ImplementWithModreq_02() { var il = @" .class interface public abstract auto ansi CL1 { .method public hidebysig newslot specialname abstract virtual instance int32 modreq([mscorlib]System.Runtime.CompilerServices.IsConst) get_P() cil managed { } .property instance int32 modreq([mscorlib]System.Runtime.CompilerServices.IsConst) P() { .get instance int32 modreq([mscorlib]System.Runtime.CompilerServices.IsConst) CL1::get_P() } } // end of class CL1 "; var source = @" class Test1 : CL1 { public int P { get => throw null; } } class Test2 : CL1 { int CL1.P { get => throw null; } } "; CreateCompilationWithIL(source, il).VerifyDiagnostics( // (6,9): error CS0686: Accessor 'Test1.P.get' cannot implement interface member 'CL1.get_P()' for type 'Test1'. Use an explicit interface implementation. // get => throw null; Diagnostic(ErrorCode.ERR_AccessorImplementingMethod, "get").WithArguments("Test1.P.get", "CL1.get_P()", "Test1").WithLocation(6, 9), // (12,13): error CS0682: 'Test2.CL1.P' cannot implement 'CL1.P' because it is not supported by the language // int CL1.P Diagnostic(ErrorCode.ERR_BogusExplicitImpl, "P").WithArguments("Test2.CL1.P", "CL1.P").WithLocation(12, 13), // (14,9): error CS0570: 'CL1.get_P()' is not supported by the language // get => throw null; Diagnostic(ErrorCode.ERR_BindToBogus, "get").WithArguments("CL1.get_P()").WithLocation(14, 9) ); } [Fact] public void ImplementWithModreq_03() { var il = @" .class interface public abstract auto ansi CL1 { .method public hidebysig newslot specialname abstract virtual instance int32 modreq([mscorlib]System.Runtime.CompilerServices.IsConst) get_P() cil managed { } .property instance int32 P() { .get instance int32 modreq([mscorlib]System.Runtime.CompilerServices.IsConst) CL1::get_P() } } // end of class CL1 "; var source = @" class Test1 : CL1 { public int P { get => throw null; } } class Test2 : CL1 { int CL1.P { get => throw null; } } "; CreateCompilationWithIL(source, il).VerifyDiagnostics( // (6,9): error CS0570: 'CL1.P.get' is not supported by the language // get => throw null; Diagnostic(ErrorCode.ERR_BindToBogus, "get").WithArguments("CL1.P.get").WithLocation(6, 9), // (14,9): error CS0570: 'CL1.P.get' is not supported by the language // get => throw null; Diagnostic(ErrorCode.ERR_BindToBogus, "get").WithArguments("CL1.P.get").WithLocation(14, 9) ); } [Fact] public void ImplementWithModreq_04() { var il = @" .class interface public abstract auto ansi CL1 { .method public hidebysig newslot specialname abstract virtual instance void modreq([mscorlib]System.Runtime.CompilerServices.IsConst) set_P(int32 x) cil managed { } .property instance int32 P() { .set instance void modreq([mscorlib]System.Runtime.CompilerServices.IsConst) CL1::set_P(int32) } } // end of class CL1 "; var source = @" class Test1 : CL1 { public int P { set => throw null; } } class Test2 : CL1 { int CL1.P { set => throw null; } } "; CreateCompilationWithIL(source, il).VerifyDiagnostics( // (6,9): error CS0570: 'CL1.P.set' is not supported by the language // set => throw null; Diagnostic(ErrorCode.ERR_BindToBogus, "set").WithArguments("CL1.P.set").WithLocation(6, 9), // (14,9): error CS0570: 'CL1.P.set' is not supported by the language // set => throw null; Diagnostic(ErrorCode.ERR_BindToBogus, "set").WithArguments("CL1.P.set").WithLocation(14, 9) ); } [Fact] public void ImplementWithModreq_05() { var il = @" .class interface public abstract auto ansi CL1 { .method public hidebysig newslot specialname abstract virtual instance int32 modreq([mscorlib]System.Runtime.CompilerServices.IsConst) get_P() cil managed { } .method public hidebysig newslot specialname abstract virtual instance void modreq([mscorlib]System.Runtime.CompilerServices.IsConst) set_P(int32 x) cil managed { } .property instance int32 P() { .get instance int32 modreq([mscorlib]System.Runtime.CompilerServices.IsConst) CL1::get_P() .set instance void modreq([mscorlib]System.Runtime.CompilerServices.IsConst) CL1::set_P(int32) } } // end of class CL1 "; var source = @" class Test1 : CL1 { public int P { get => throw null; set => throw null; } } class Test2 : CL1 { int CL1.P { get => throw null; set => throw null; } } "; CreateCompilationWithIL(source, il).VerifyDiagnostics( // (6,9): error CS0570: 'CL1.P.get' is not supported by the language // get => throw null; Diagnostic(ErrorCode.ERR_BindToBogus, "get").WithArguments("CL1.P.get").WithLocation(6, 9), // (7,9): error CS0570: 'CL1.P.set' is not supported by the language // set => throw null; Diagnostic(ErrorCode.ERR_BindToBogus, "set").WithArguments("CL1.P.set").WithLocation(7, 9), // (15,9): error CS0570: 'CL1.P.get' is not supported by the language // get => throw null; Diagnostic(ErrorCode.ERR_BindToBogus, "get").WithArguments("CL1.P.get").WithLocation(15, 9), // (16,9): error CS0570: 'CL1.P.set' is not supported by the language // set => throw null; Diagnostic(ErrorCode.ERR_BindToBogus, "set").WithArguments("CL1.P.set").WithLocation(16, 9) ); } [Fact] public void ImplementWithModreq_06() { var il = @" .class interface public abstract auto ansi CL1 { .method public hidebysig newslot specialname abstract virtual instance int32 get_P() cil managed { } .method public hidebysig newslot specialname abstract virtual instance void modreq([mscorlib]System.Runtime.CompilerServices.IsConst) set_P(int32 x) cil managed { } .property instance int32 P() { .get instance int32 CL1::get_P() .set instance void modreq([mscorlib]System.Runtime.CompilerServices.IsConst) CL1::set_P(int32) } } // end of class CL1 "; var source = @" class Test1 : CL1 { public int P { get => throw null; set => throw null; } } class Test2 : CL1 { int CL1.P { get => throw null; set => throw null; } } "; CreateCompilationWithIL(source, il).VerifyDiagnostics( // (7,9): error CS0570: 'CL1.P.set' is not supported by the language // set => throw null; Diagnostic(ErrorCode.ERR_BindToBogus, "set").WithArguments("CL1.P.set").WithLocation(7, 9), // (16,9): error CS0570: 'CL1.P.set' is not supported by the language // set => throw null; Diagnostic(ErrorCode.ERR_BindToBogus, "set").WithArguments("CL1.P.set").WithLocation(16, 9) ); } [Fact] public void ImplementWithModreq_07() { var il = @" .class interface public abstract auto ansi CL1 { .method public hidebysig newslot specialname abstract virtual instance int32 modreq([mscorlib]System.Runtime.CompilerServices.IsConst) get_P() cil managed { } .method public hidebysig newslot specialname abstract virtual instance void set_P(int32 x) cil managed { } .property instance int32 P() { .get instance int32 modreq([mscorlib]System.Runtime.CompilerServices.IsConst) CL1::get_P() .set instance void CL1::set_P(int32) } } // end of class CL1 "; var source = @" class Test1 : CL1 { public int P { get => throw null; set => throw null; } } class Test2 : CL1 { int CL1.P { get => throw null; set => throw null; } } "; CreateCompilationWithIL(source, il).VerifyDiagnostics( // (6,9): error CS0570: 'CL1.P.get' is not supported by the language // get => throw null; Diagnostic(ErrorCode.ERR_BindToBogus, "get").WithArguments("CL1.P.get").WithLocation(6, 9), // (15,9): error CS0570: 'CL1.P.get' is not supported by the language // get => throw null; Diagnostic(ErrorCode.ERR_BindToBogus, "get").WithArguments("CL1.P.get").WithLocation(15, 9) ); } [Fact] public void ImplementWithModreq_08() { var il = @" .class interface public abstract auto ansi CL1 { .method public hidebysig specialname newslot abstract virtual instance void add_E ( class [mscorlib]System.Action modreq([mscorlib]System.Runtime.CompilerServices.IsConst) 'value' ) cil managed { } .method public hidebysig specialname newslot abstract virtual instance void remove_E ( class [mscorlib]System.Action modreq([mscorlib]System.Runtime.CompilerServices.IsConst) 'value' ) cil managed { } .event [mscorlib]System.Action E { .addon instance void CL1::add_E(class [mscorlib]System.Action modreq([mscorlib]System.Runtime.CompilerServices.IsConst)) .removeon instance void CL1::remove_E(class [mscorlib]System.Action modreq([mscorlib]System.Runtime.CompilerServices.IsConst)) } } // end of class CL1 "; var source = @" class Test1 : CL1 { public event System.Action E { add => throw null; remove => throw null; } } class Test2 : CL1 { event System.Action CL1.E { add => throw null; remove => throw null; } } "; CreateCompilationWithIL(source, il).VerifyDiagnostics( // (6,9): error CS0570: 'CL1.E.add' is not supported by the language // add => throw null; Diagnostic(ErrorCode.ERR_BindToBogus, "add").WithArguments("CL1.E.add").WithLocation(6, 9), // (7,9): error CS0570: 'CL1.E.remove' is not supported by the language // remove => throw null; Diagnostic(ErrorCode.ERR_BindToBogus, "remove").WithArguments("CL1.E.remove").WithLocation(7, 9), // (15,9): error CS0570: 'CL1.E.add' is not supported by the language // add => throw null; Diagnostic(ErrorCode.ERR_BindToBogus, "add").WithArguments("CL1.E.add").WithLocation(15, 9), // (16,9): error CS0570: 'CL1.E.remove' is not supported by the language // remove => throw null; Diagnostic(ErrorCode.ERR_BindToBogus, "remove").WithArguments("CL1.E.remove").WithLocation(16, 9) ); } [Fact] public void ImplementWithModreq_09() { var il = @" .class interface public abstract auto ansi CL1 { .method public hidebysig specialname newslot abstract virtual instance void add_E ( class [mscorlib]System.Action 'value' ) cil managed { } .method public hidebysig specialname newslot abstract virtual instance void remove_E ( class [mscorlib]System.Action modreq([mscorlib]System.Runtime.CompilerServices.IsConst) 'value' ) cil managed { } .event [mscorlib]System.Action E { .addon instance void CL1::add_E(class [mscorlib]System.Action) .removeon instance void CL1::remove_E(class [mscorlib]System.Action modreq([mscorlib]System.Runtime.CompilerServices.IsConst)) } } // end of class CL1 "; var source = @" class Test1 : CL1 { public event System.Action E { add => throw null; remove => throw null; } } class Test2 : CL1 { event System.Action CL1.E { add => throw null; remove => throw null; } } "; CreateCompilationWithIL(source, il).VerifyDiagnostics( // (7,9): error CS0570: 'CL1.E.remove' is not supported by the language // remove => throw null; Diagnostic(ErrorCode.ERR_BindToBogus, "remove").WithArguments("CL1.E.remove").WithLocation(7, 9), // (16,9): error CS0570: 'CL1.E.remove' is not supported by the language // remove => throw null; Diagnostic(ErrorCode.ERR_BindToBogus, "remove").WithArguments("CL1.E.remove").WithLocation(16, 9) ); } [Fact] public void ImplementWithModreq_10() { var il = @" .class interface public abstract auto ansi CL1 { .method public hidebysig specialname newslot abstract virtual instance void add_E ( class [mscorlib]System.Action modreq([mscorlib]System.Runtime.CompilerServices.IsConst) 'value' ) cil managed { } .method public hidebysig specialname newslot abstract virtual instance void remove_E ( class [mscorlib]System.Action 'value' ) cil managed { } .event [mscorlib]System.Action E { .addon instance void CL1::add_E(class [mscorlib]System.Action modreq([mscorlib]System.Runtime.CompilerServices.IsConst)) .removeon instance void CL1::remove_E(class [mscorlib]System.Action) } } // end of class CL1 "; var source = @" class Test1 : CL1 { public event System.Action E { add => throw null; remove => throw null; } } class Test2 : CL1 { event System.Action CL1.E { add => throw null; remove => throw null; } } "; CreateCompilationWithIL(source, il).VerifyDiagnostics( // (6,9): error CS0570: 'CL1.E.add' is not supported by the language // add => throw null; Diagnostic(ErrorCode.ERR_BindToBogus, "add").WithArguments("CL1.E.add").WithLocation(6, 9), // (15,9): error CS0570: 'CL1.E.add' is not supported by the language // add => throw null; Diagnostic(ErrorCode.ERR_BindToBogus, "add").WithArguments("CL1.E.add").WithLocation(15, 9) ); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { /// <summary> /// Tests related to use site errors. /// </summary> public class UseSiteErrorTests : CSharpTestBase { [Fact] public void TestFields() { var text = @" public class C { public CSharpErrors.Subclass1 Field; }"; CompileWithMissingReference(text).VerifyDiagnostics(); } [Fact] public void TestOverrideMethodReturnType() { var text = @" class C : CSharpErrors.ClassMethods { public override UnavailableClass ReturnType1() { return null; } public override UnavailableClass[] ReturnType2() { return null; } }"; CompileWithMissingReference(text).VerifyDiagnostics( // (4,21): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // public override UnavailableClass ReturnType1() { return null; } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass"), // (5,21): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // public override UnavailableClass[] ReturnType2() { return null; } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass"), // (4,38): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public override UnavailableClass ReturnType1() { return null; } Diagnostic(ErrorCode.ERR_NoTypeDef, "ReturnType1").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (5,40): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public override UnavailableClass[] ReturnType2() { return null; } Diagnostic(ErrorCode.ERR_NoTypeDef, "ReturnType2").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); } [Fact] public void TestOverrideMethodReturnTypeModOpt() { var text = @" class C : ILErrors.ClassMethods { public override int ReturnType1() { return 0; } public override int[] ReturnType2() { return null; } }"; CompileWithMissingReference(text).VerifyDiagnostics( // (4,25): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public override int ReturnType1() { return 0; } Diagnostic(ErrorCode.ERR_NoTypeDef, "ReturnType1").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (5,27): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public override int[] ReturnType2() { return null; } Diagnostic(ErrorCode.ERR_NoTypeDef, "ReturnType2").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); } [Fact] public void TestOverrideMethodParameterType() { var text = @" class C : CSharpErrors.ClassMethods { public override void ParameterType1(UnavailableClass x) { } public override void ParameterType2(UnavailableClass[] x) { } }"; CompileWithMissingReference(text).VerifyDiagnostics( // (4,41): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // public override void ParameterType1(UnavailableClass x) { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass"), // (5,41): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // public override void ParameterType2(UnavailableClass[] x) { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass")); } [Fact] public void TestOverrideMethodParameterTypeModOpt() { var text = @" class C : ILErrors.ClassMethods { public override void ParameterType1(int x) { } public override void ParameterType2(int[] x) { } }"; CompileWithMissingReference(text).VerifyDiagnostics( // (4,26): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public override void ParameterType1(int x) { } Diagnostic(ErrorCode.ERR_NoTypeDef, "ParameterType1").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (5,26): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public override void ParameterType2(int[] x) { } Diagnostic(ErrorCode.ERR_NoTypeDef, "ParameterType2").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); } [Fact] public void TestImplicitlyImplementMethod() { var text = @" class C : CSharpErrors.InterfaceMethods { public UnavailableClass ReturnType1() { return null; } public UnavailableClass[] ReturnType2() { return null; } public void ParameterType1(UnavailableClass x) { } public void ParameterType2(UnavailableClass[] x) { } }"; CompileWithMissingReference(text).VerifyDiagnostics( // (5,12): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // public UnavailableClass[] ReturnType2() { return null; } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass").WithLocation(5, 12), // (6,32): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // public void ParameterType1(UnavailableClass x) { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass").WithLocation(6, 32), // (7,32): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // public void ParameterType2(UnavailableClass[] x) { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass").WithLocation(7, 32), // (4,12): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // public UnavailableClass ReturnType1() { return null; } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass").WithLocation(4, 12), // (2,11): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // class C : CSharpErrors.InterfaceMethods Diagnostic(ErrorCode.ERR_NoTypeDef, "CSharpErrors.InterfaceMethods").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 11), // (2,11): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // class C : CSharpErrors.InterfaceMethods Diagnostic(ErrorCode.ERR_NoTypeDef, "CSharpErrors.InterfaceMethods").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 11), // (2,11): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // class C : CSharpErrors.InterfaceMethods Diagnostic(ErrorCode.ERR_NoTypeDef, "CSharpErrors.InterfaceMethods").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 11), // (2,11): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // class C : CSharpErrors.InterfaceMethods Diagnostic(ErrorCode.ERR_NoTypeDef, "CSharpErrors.InterfaceMethods").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 11) ); } [Fact] public void TestImplicitlyImplementMethodModOpt() { var text = @" class C : ILErrors.InterfaceMethods { public int ReturnType1() { return 0; } public int[] ReturnType2() { return null; } public void ParameterType1(int x) { } public void ParameterType2(int[] x) { } }"; CompileWithMissingReference(text).VerifyDiagnostics( // (4,16): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public int ReturnType1() { return 0; } Diagnostic(ErrorCode.ERR_NoTypeDef, "ReturnType1").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (5,18): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public int[] ReturnType2() { return null; } Diagnostic(ErrorCode.ERR_NoTypeDef, "ReturnType2").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (6,17): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public void ParameterType1(int x) { } Diagnostic(ErrorCode.ERR_NoTypeDef, "ParameterType1").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (7,17): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public void ParameterType2(int[] x) { } Diagnostic(ErrorCode.ERR_NoTypeDef, "ParameterType2").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); } [Fact] public void TestExplicitlyImplementMethod() { var text = @" class C : CSharpErrors.InterfaceMethods { UnavailableClass CSharpErrors.InterfaceMethods.ReturnType1() { return null; } UnavailableClass[] CSharpErrors.InterfaceMethods.ReturnType2() { return null; } void CSharpErrors.InterfaceMethods.ParameterType1(UnavailableClass x) { } void CSharpErrors.InterfaceMethods.ParameterType2(UnavailableClass[] x) { } }"; CompileWithMissingReference(text).VerifyDiagnostics( // (5,5): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // UnavailableClass[] CSharpErrors.InterfaceMethods.ReturnType2() { return null; } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass").WithLocation(5, 5), // (5,54): error CS0539: 'C.ReturnType2()' in explicit interface declaration is not a member of interface // UnavailableClass[] CSharpErrors.InterfaceMethods.ReturnType2() { return null; } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "ReturnType2").WithArguments("C.ReturnType2()").WithLocation(5, 54), // (6,55): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // void CSharpErrors.InterfaceMethods.ParameterType1(UnavailableClass x) { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass").WithLocation(6, 55), // (6,40): error CS0539: 'C.ParameterType1(UnavailableClass)' in explicit interface declaration is not a member of interface // void CSharpErrors.InterfaceMethods.ParameterType1(UnavailableClass x) { } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "ParameterType1").WithArguments("C.ParameterType1(UnavailableClass)").WithLocation(6, 40), // (7,55): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // void CSharpErrors.InterfaceMethods.ParameterType2(UnavailableClass[] x) { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass").WithLocation(7, 55), // (7,40): error CS0539: 'C.ParameterType2(UnavailableClass[])' in explicit interface declaration is not a member of interface // void CSharpErrors.InterfaceMethods.ParameterType2(UnavailableClass[] x) { } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "ParameterType2").WithArguments("C.ParameterType2(UnavailableClass[])").WithLocation(7, 40), // (4,5): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // UnavailableClass CSharpErrors.InterfaceMethods.ReturnType1() { return null; } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass").WithLocation(4, 5), // (4,52): error CS0539: 'C.ReturnType1()' in explicit interface declaration is not a member of interface // UnavailableClass CSharpErrors.InterfaceMethods.ReturnType1() { return null; } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "ReturnType1").WithArguments("C.ReturnType1()").WithLocation(4, 52), // (2,11): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // class C : CSharpErrors.InterfaceMethods Diagnostic(ErrorCode.ERR_NoTypeDef, "CSharpErrors.InterfaceMethods").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 11), // (2,11): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // class C : CSharpErrors.InterfaceMethods Diagnostic(ErrorCode.ERR_NoTypeDef, "CSharpErrors.InterfaceMethods").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 11), // (2,11): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // class C : CSharpErrors.InterfaceMethods Diagnostic(ErrorCode.ERR_NoTypeDef, "CSharpErrors.InterfaceMethods").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 11), // (2,11): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // class C : CSharpErrors.InterfaceMethods Diagnostic(ErrorCode.ERR_NoTypeDef, "CSharpErrors.InterfaceMethods").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 11) ); } [Fact] public void TestExplicitlyImplementMethodModOpt() { var text = @" class C : ILErrors.InterfaceMethods { int ILErrors.InterfaceMethods.ReturnType1() { return 0; } int[] ILErrors.InterfaceMethods.ReturnType2() { return null; } void ILErrors.InterfaceMethods.ParameterType1(int x) { } void ILErrors.InterfaceMethods.ParameterType2(int[] x) { } }"; CompileWithMissingReference(text).VerifyDiagnostics( // (4,16): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public int ReturnType1() { return 0; } Diagnostic(ErrorCode.ERR_NoTypeDef, "ReturnType1").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (5,18): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public int[] ReturnType2() { return null; } Diagnostic(ErrorCode.ERR_NoTypeDef, "ReturnType2").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (6,17): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public void ParameterType1(int x) { } Diagnostic(ErrorCode.ERR_NoTypeDef, "ParameterType1").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (7,17): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public void ParameterType2(int[] x) { } Diagnostic(ErrorCode.ERR_NoTypeDef, "ParameterType2").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); } [Fact] public void TestOverridePropertyType() { var text = @" class C : CSharpErrors.ClassProperties { public override UnavailableClass Get1 { get { return null; } } public override UnavailableClass[] Get2 { get { return null; } } public override UnavailableClass Set1 { set { } } public override UnavailableClass[] Set2 { set { } } public override UnavailableClass GetSet1 { get { return null; } set { } } public override UnavailableClass[] GetSet2 { get { return null; } set { } } }"; CompileWithMissingReference(text).VerifyDiagnostics( // (4,21): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // public override UnavailableClass Get1 { get { return null; } } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass"), // (5,21): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // public override UnavailableClass[] Get2 { get { return null; } } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass"), // (7,21): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // public override UnavailableClass Set1 { set { } } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass"), // (8,21): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // public override UnavailableClass[] Set2 { set { } } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass"), // (10,21): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // public override UnavailableClass GetSet1 { get { return null; } set { } } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass"), // (11,21): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // public override UnavailableClass[] GetSet2 { get { return null; } set { } } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass"), // (4,38): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public override UnavailableClass Get1 { get { return null; } } Diagnostic(ErrorCode.ERR_NoTypeDef, "Get1").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (5,40): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public override UnavailableClass[] Get2 { get { return null; } } Diagnostic(ErrorCode.ERR_NoTypeDef, "Get2").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (7,38): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public override UnavailableClass Set1 { set { } } Diagnostic(ErrorCode.ERR_NoTypeDef, "Set1").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (8,40): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public override UnavailableClass[] Set2 { set { } } Diagnostic(ErrorCode.ERR_NoTypeDef, "Set2").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (10,38): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public override UnavailableClass GetSet1 { get { return null; } set { } } Diagnostic(ErrorCode.ERR_NoTypeDef, "GetSet1").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (11,40): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public override UnavailableClass[] GetSet2 { get { return null; } set { } } Diagnostic(ErrorCode.ERR_NoTypeDef, "GetSet2").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); } [Fact] public void TestOverridePropertyTypeModOpt() { var text = @" class C : ILErrors.ClassProperties { public override int Get1 { get { return 0; } } public override int[] Get2 { get { return null; } } public override int Set1 { set { } } public override int[] Set2 { set { } } public override int GetSet1 { get { return 0; } set { } } public override int[] GetSet2 { get { return null; } set { } } }"; CompileWithMissingReference(text).VerifyDiagnostics( // (4,25): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public override int Get1 { get { return 0; } } Diagnostic(ErrorCode.ERR_NoTypeDef, "Get1").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (5,27): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public override int[] Get2 { get { return null; } } Diagnostic(ErrorCode.ERR_NoTypeDef, "Get2").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (7,25): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public override int Set1 { set { } } Diagnostic(ErrorCode.ERR_NoTypeDef, "Set1").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (8,27): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public override int[] Set2 { set { } } Diagnostic(ErrorCode.ERR_NoTypeDef, "Set2").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (10,25): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public override int GetSet1 { get { return 0; } set { } } Diagnostic(ErrorCode.ERR_NoTypeDef, "GetSet1").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (11,27): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public override int[] GetSet2 { get { return null; } set { } } Diagnostic(ErrorCode.ERR_NoTypeDef, "GetSet2").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); } [Fact] public void TestImplicitlyImplementProperty() { var text = @" class C : CSharpErrors.InterfaceProperties { public UnavailableClass Get1 { get { return null; } } public UnavailableClass[] Get2 { get { return null; } } public UnavailableClass Set1 { set { } } public UnavailableClass[] Set2 { set { } } public UnavailableClass GetSet1 { get { return null; } set { } } public UnavailableClass[] GetSet2 { get { return null; } set { } } }"; CompileWithMissingReference(text).VerifyDiagnostics( // (5,12): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // public UnavailableClass[] Get2 { get { return null; } } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass").WithLocation(5, 12), // (7,12): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // public UnavailableClass Set1 { set { } } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass").WithLocation(7, 12), // (8,12): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // public UnavailableClass[] Set2 { set { } } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass").WithLocation(8, 12), // (10,12): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // public UnavailableClass GetSet1 { get { return null; } set { } } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass").WithLocation(10, 12), // (11,12): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // public UnavailableClass[] GetSet2 { get { return null; } set { } } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass").WithLocation(11, 12), // (4,12): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // public UnavailableClass Get1 { get { return null; } } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass").WithLocation(4, 12), // (2,11): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // class C : CSharpErrors.InterfaceProperties Diagnostic(ErrorCode.ERR_NoTypeDef, "CSharpErrors.InterfaceProperties").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 11), // (2,11): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // class C : CSharpErrors.InterfaceProperties Diagnostic(ErrorCode.ERR_NoTypeDef, "CSharpErrors.InterfaceProperties").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 11), // (2,11): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // class C : CSharpErrors.InterfaceProperties Diagnostic(ErrorCode.ERR_NoTypeDef, "CSharpErrors.InterfaceProperties").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 11), // (2,11): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // class C : CSharpErrors.InterfaceProperties Diagnostic(ErrorCode.ERR_NoTypeDef, "CSharpErrors.InterfaceProperties").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 11), // (2,11): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // class C : CSharpErrors.InterfaceProperties Diagnostic(ErrorCode.ERR_NoTypeDef, "CSharpErrors.InterfaceProperties").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 11), // (2,11): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // class C : CSharpErrors.InterfaceProperties Diagnostic(ErrorCode.ERR_NoTypeDef, "CSharpErrors.InterfaceProperties").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 11) ); } [Fact] public void TestImplicitlyImplementPropertyModOpt() { var text = @" class C : ILErrors.InterfaceProperties { public int Get1 { get { return 0; } } public int[] Get2 { get { return null; } } public int Set1 { set { } } public int[] Set2 { set { } } public int GetSet1 { get { return 0; } set { } } public int[] GetSet2 { get { return null; } set { } } }"; CompileWithMissingReference(text).VerifyDiagnostics( // (10,44): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public int GetSet1 { get { return 0; } set { } } Diagnostic(ErrorCode.ERR_NoTypeDef, "set").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (11,28): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public int[] GetSet2 { get { return null; } set { } } Diagnostic(ErrorCode.ERR_NoTypeDef, "get").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (11,49): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public int[] GetSet2 { get { return null; } set { } } Diagnostic(ErrorCode.ERR_NoTypeDef, "set").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (4,23): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public int Get1 { get { return 0; } } Diagnostic(ErrorCode.ERR_NoTypeDef, "get").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (5,25): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public int[] Get2 { get { return null; } } Diagnostic(ErrorCode.ERR_NoTypeDef, "get").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (7,23): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public int Set1 { set { } } Diagnostic(ErrorCode.ERR_NoTypeDef, "set").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (8,25): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public int[] Set2 { set { } } Diagnostic(ErrorCode.ERR_NoTypeDef, "set").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (10,26): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public int GetSet1 { get { return 0; } set { } } Diagnostic(ErrorCode.ERR_NoTypeDef, "get").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); } [Fact] public void TestExplicitlyImplementProperty() { var text = @" class C : CSharpErrors.InterfaceProperties { UnavailableClass CSharpErrors.InterfaceProperties.Get1 { get { return null; } } UnavailableClass[] CSharpErrors.InterfaceProperties.Get2 { get { return null; } } UnavailableClass CSharpErrors.InterfaceProperties.Set1 { set { } } UnavailableClass[] CSharpErrors.InterfaceProperties.Set2 { set { } } UnavailableClass CSharpErrors.InterfaceProperties.GetSet1 { get { return null; } set { } } UnavailableClass[] CSharpErrors.InterfaceProperties.GetSet2 { get { return null; } set { } } }"; CompileWithMissingReference(text).VerifyDiagnostics( // (4,5): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // UnavailableClass CSharpErrors.InterfaceProperties.Get1 { get { return null; } } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass").WithLocation(4, 5), // (4,55): error CS0539: 'C.Get1' in explicit interface declaration is not a member of interface // UnavailableClass CSharpErrors.InterfaceProperties.Get1 { get { return null; } } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Get1").WithArguments("C.Get1").WithLocation(4, 55), // (5,5): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // UnavailableClass[] CSharpErrors.InterfaceProperties.Get2 { get { return null; } } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass").WithLocation(5, 5), // (5,57): error CS0539: 'C.Get2' in explicit interface declaration is not a member of interface // UnavailableClass[] CSharpErrors.InterfaceProperties.Get2 { get { return null; } } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Get2").WithArguments("C.Get2").WithLocation(5, 57), // (7,5): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // UnavailableClass CSharpErrors.InterfaceProperties.Set1 { set { } } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass").WithLocation(7, 5), // (7,55): error CS0539: 'C.Set1' in explicit interface declaration is not a member of interface // UnavailableClass CSharpErrors.InterfaceProperties.Set1 { set { } } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Set1").WithArguments("C.Set1").WithLocation(7, 55), // (8,5): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // UnavailableClass[] CSharpErrors.InterfaceProperties.Set2 { set { } } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass").WithLocation(8, 5), // (8,57): error CS0539: 'C.Set2' in explicit interface declaration is not a member of interface // UnavailableClass[] CSharpErrors.InterfaceProperties.Set2 { set { } } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Set2").WithArguments("C.Set2").WithLocation(8, 57), // (10,5): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // UnavailableClass CSharpErrors.InterfaceProperties.GetSet1 { get { return null; } set { } } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass").WithLocation(10, 5), // (10,55): error CS0539: 'C.GetSet1' in explicit interface declaration is not a member of interface // UnavailableClass CSharpErrors.InterfaceProperties.GetSet1 { get { return null; } set { } } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "GetSet1").WithArguments("C.GetSet1").WithLocation(10, 55), // (11,5): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // UnavailableClass[] CSharpErrors.InterfaceProperties.GetSet2 { get { return null; } set { } } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass").WithLocation(11, 5), // (11,57): error CS0539: 'C.GetSet2' in explicit interface declaration is not a member of interface // UnavailableClass[] CSharpErrors.InterfaceProperties.GetSet2 { get { return null; } set { } } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "GetSet2").WithArguments("C.GetSet2").WithLocation(11, 57), // (2,11): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // class C : CSharpErrors.InterfaceProperties Diagnostic(ErrorCode.ERR_NoTypeDef, "CSharpErrors.InterfaceProperties").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 11), // (2,11): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // class C : CSharpErrors.InterfaceProperties Diagnostic(ErrorCode.ERR_NoTypeDef, "CSharpErrors.InterfaceProperties").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 11), // (2,11): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // class C : CSharpErrors.InterfaceProperties Diagnostic(ErrorCode.ERR_NoTypeDef, "CSharpErrors.InterfaceProperties").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 11), // (2,11): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // class C : CSharpErrors.InterfaceProperties Diagnostic(ErrorCode.ERR_NoTypeDef, "CSharpErrors.InterfaceProperties").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 11), // (2,11): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // class C : CSharpErrors.InterfaceProperties Diagnostic(ErrorCode.ERR_NoTypeDef, "CSharpErrors.InterfaceProperties").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 11), // (2,11): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // class C : CSharpErrors.InterfaceProperties Diagnostic(ErrorCode.ERR_NoTypeDef, "CSharpErrors.InterfaceProperties").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 11) ); } [Fact] public void TestExplicitlyImplementPropertyModOpt() { var text = @" class C : ILErrors.InterfaceProperties { int ILErrors.InterfaceProperties.Get1 { get { return 0; } } int[] ILErrors.InterfaceProperties.Get2 { get { return null; } } int ILErrors.InterfaceProperties.Set1 { set { } } int[] ILErrors.InterfaceProperties.Set2 { set { } } int ILErrors.InterfaceProperties.GetSet1 { get { return 0; } set { } } int[] ILErrors.InterfaceProperties.GetSet2 { get { return null; } set { } } }"; CompileWithMissingReference(text).VerifyDiagnostics( // (10,66): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // int ILErrors.InterfaceProperties.GetSet1 { get { return 0; } set { } } Diagnostic(ErrorCode.ERR_NoTypeDef, "set").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (11,50): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // int[] ILErrors.InterfaceProperties.GetSet2 { get { return null; } set { } } Diagnostic(ErrorCode.ERR_NoTypeDef, "get").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (11,71): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // int[] ILErrors.InterfaceProperties.GetSet2 { get { return null; } set { } } Diagnostic(ErrorCode.ERR_NoTypeDef, "set").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (4,45): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // int ILErrors.InterfaceProperties.Get1 { get { return 0; } } Diagnostic(ErrorCode.ERR_NoTypeDef, "get").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (5,47): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // int[] ILErrors.InterfaceProperties.Get2 { get { return null; } } Diagnostic(ErrorCode.ERR_NoTypeDef, "get").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (7,45): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // int ILErrors.InterfaceProperties.Set1 { set { } } Diagnostic(ErrorCode.ERR_NoTypeDef, "set").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (8,47): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // int[] ILErrors.InterfaceProperties.Set2 { set { } } Diagnostic(ErrorCode.ERR_NoTypeDef, "set").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (10,48): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // int ILErrors.InterfaceProperties.GetSet1 { get { return 0; } set { } } Diagnostic(ErrorCode.ERR_NoTypeDef, "get").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); } [Fact] public void TestPropertyAccessorModOpt() { var text = @"class C : ILErrors.ClassProperties { static void M(ILErrors.ClassProperties c) { c.GetSet1 = c.GetSet1; c.GetSet2 = c.GetSet2; c.GetSet3 = c.GetSet3; } void M() { GetSet3 = GetSet3; } }"; CompileWithMissingReference(text).VerifyDiagnostics( // (5,11): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // c.GetSet1 = c.GetSet1; Diagnostic(ErrorCode.ERR_NoTypeDef, "GetSet1").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(5, 11), // (5,23): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // c.GetSet1 = c.GetSet1; Diagnostic(ErrorCode.ERR_NoTypeDef, "GetSet1").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(5, 23), // (6,11): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // c.GetSet2 = c.GetSet2; Diagnostic(ErrorCode.ERR_NoTypeDef, "GetSet2").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 11), // (6,23): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // c.GetSet2 = c.GetSet2; Diagnostic(ErrorCode.ERR_NoTypeDef, "GetSet2").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 23), // (7,11): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // c.GetSet3 = c.GetSet3; Diagnostic(ErrorCode.ERR_NoTypeDef, "GetSet3").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 11), // (7,23): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // c.GetSet3 = c.GetSet3; Diagnostic(ErrorCode.ERR_NoTypeDef, "GetSet3").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 23), // (11,9): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // GetSet3 = GetSet3; Diagnostic(ErrorCode.ERR_NoTypeDef, "GetSet3").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(11, 9), // (11,19): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // GetSet3 = GetSet3; Diagnostic(ErrorCode.ERR_NoTypeDef, "GetSet3").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(11, 19)); } [Fact] public void TestOverrideEventType_FieldLike() { var text = @" class C : CSharpErrors.ClassEvents { public override event UnavailableDelegate Event1; public override event CSharpErrors.EventDelegate<UnavailableClass> Event2; public override event CSharpErrors.EventDelegate<UnavailableClass[]> Event3; void UseEvent() { Event1(); Event2(); Event3(); } }"; CompileWithMissingReference(text).VerifyDiagnostics( // (4,27): error CS0246: The type or namespace name 'UnavailableDelegate' could not be found (are you missing a using directive or an assembly reference?) // public override event UnavailableDelegate Event1; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableDelegate").WithArguments("UnavailableDelegate"), // (5,54): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // public override event CSharpErrors.EventDelegate<UnavailableClass> Event2; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass"), // (6,54): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // public override event CSharpErrors.EventDelegate<UnavailableClass[]> Event3; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass"), // (4,47): error CS0012: The type 'UnavailableDelegate' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public override event UnavailableDelegate Event1; Diagnostic(ErrorCode.ERR_NoTypeDef, "Event1").WithArguments("UnavailableDelegate", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (5,72): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public override event CSharpErrors.EventDelegate<UnavailableClass> Event2; Diagnostic(ErrorCode.ERR_NoTypeDef, "Event2").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (6,74): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public override event CSharpErrors.EventDelegate<UnavailableClass[]> Event3; Diagnostic(ErrorCode.ERR_NoTypeDef, "Event3").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); } [Fact] public void TestOverrideEventType_Custom() { var text = @" class C : CSharpErrors.ClassEvents { public override event UnavailableDelegate Event1 { add { } remove { } } public override event CSharpErrors.EventDelegate<UnavailableClass> Event2 { add { } remove { } } public override event CSharpErrors.EventDelegate<UnavailableClass[]> Event3 { add { } remove { } } }"; CompileWithMissingReference(text).VerifyDiagnostics( // (4,27): error CS0246: The type or namespace name 'UnavailableDelegate' could not be found (are you missing a using directive or an assembly reference?) // public override event UnavailableDelegate Event1; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableDelegate").WithArguments("UnavailableDelegate"), // (5,54): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // public override event CSharpErrors.EventDelegate<UnavailableClass> Event2; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass"), // (6,54): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // public override event CSharpErrors.EventDelegate<UnavailableClass[]> Event3; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass"), // (4,47): error CS0012: The type 'UnavailableDelegate' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public override event UnavailableDelegate Event1; Diagnostic(ErrorCode.ERR_NoTypeDef, "Event1").WithArguments("UnavailableDelegate", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (5,72): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public override event CSharpErrors.EventDelegate<UnavailableClass> Event2; Diagnostic(ErrorCode.ERR_NoTypeDef, "Event2").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (6,74): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public override event CSharpErrors.EventDelegate<UnavailableClass[]> Event3; Diagnostic(ErrorCode.ERR_NoTypeDef, "Event3").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); } [Fact] public void TestOverrideEventTypeModOpt_FieldLike() { var text = @" class C : ILErrors.ClassEvents { public override event System.Action<int[]> Event1; void UseEvent() { Event1(null); } }"; CompileWithMissingReference(text).VerifyDiagnostics( // (4,48): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public override event System.Action<int[]> Event1; Diagnostic(ErrorCode.ERR_NoTypeDef, "Event1").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); } [Fact] public void TestOverrideEventTypeModOpt_Custom() { var text = @" class C : ILErrors.ClassEvents { public override event System.Action<int[]> Event1 { add { } remove { } } }"; CompileWithMissingReference(text).VerifyDiagnostics( // (4,48): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public override event System.Action<int[]> Event1; Diagnostic(ErrorCode.ERR_NoTypeDef, "Event1").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); } [Fact] public void TestImplicitlyImplementEvent_FieldLike() { var text = @" class C : CSharpErrors.InterfaceEvents { public event UnavailableDelegate Event1 = () => { }; public event CSharpErrors.EventDelegate<UnavailableClass> Event2 = () => { }; public event CSharpErrors.EventDelegate<UnavailableClass[]> Event3 = () => { }; }"; CompileWithMissingReference(text).VerifyDiagnostics( // (4,18): error CS0246: The type or namespace name 'UnavailableDelegate' could not be found (are you missing a using directive or an assembly reference?) // public event UnavailableDelegate Event1 = () => { }; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableDelegate").WithArguments("UnavailableDelegate").WithLocation(4, 18), // (5,45): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // public event CSharpErrors.EventDelegate<UnavailableClass> Event2 = () => { }; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass").WithLocation(5, 45), // (6,45): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // public event CSharpErrors.EventDelegate<UnavailableClass[]> Event3 = () => { }; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass").WithLocation(6, 45), // (2,11): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // class C : CSharpErrors.InterfaceEvents Diagnostic(ErrorCode.ERR_NoTypeDef, "CSharpErrors.InterfaceEvents").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 11), // (2,11): error CS0012: The type 'UnavailableDelegate' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // class C : CSharpErrors.InterfaceEvents Diagnostic(ErrorCode.ERR_NoTypeDef, "CSharpErrors.InterfaceEvents").WithArguments("UnavailableDelegate", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 11), // (2,11): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // class C : CSharpErrors.InterfaceEvents Diagnostic(ErrorCode.ERR_NoTypeDef, "CSharpErrors.InterfaceEvents").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 11) ); } [Fact] public void TestImplicitlyImplementEvent_Custom() { var text = @" class C : CSharpErrors.InterfaceEvents { public event UnavailableDelegate Event1 { add { } remove { } } public event CSharpErrors.EventDelegate<UnavailableClass> Event2 { add { } remove { } } public event CSharpErrors.EventDelegate<UnavailableClass[]> Event3 { add { } remove { } } }"; CompileWithMissingReference(text).VerifyDiagnostics( // (4,18): error CS0246: The type or namespace name 'UnavailableDelegate' could not be found (are you missing a using directive or an assembly reference?) // public event UnavailableDelegate Event1 { add { } remove { } } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableDelegate").WithArguments("UnavailableDelegate").WithLocation(4, 18), // (5,45): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // public event CSharpErrors.EventDelegate<UnavailableClass> Event2 { add { } remove { } } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass").WithLocation(5, 45), // (6,45): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // public event CSharpErrors.EventDelegate<UnavailableClass[]> Event3 { add { } remove { } } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass").WithLocation(6, 45), // (2,11): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // class C : CSharpErrors.InterfaceEvents Diagnostic(ErrorCode.ERR_NoTypeDef, "CSharpErrors.InterfaceEvents").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 11), // (2,11): error CS0012: The type 'UnavailableDelegate' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // class C : CSharpErrors.InterfaceEvents Diagnostic(ErrorCode.ERR_NoTypeDef, "CSharpErrors.InterfaceEvents").WithArguments("UnavailableDelegate", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 11), // (2,11): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // class C : CSharpErrors.InterfaceEvents Diagnostic(ErrorCode.ERR_NoTypeDef, "CSharpErrors.InterfaceEvents").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 11) ); } [Fact] public void TestImplicitlyImplementEventModOpt_FieldLike() { var text = @" class C : ILErrors.InterfaceEvents { public event System.Action<int[]> Event1 = x => { }; }"; CompileWithMissingReference(text).VerifyDiagnostics( // (4,39): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public event System.Action<int[]> Event1 = x => { }; Diagnostic(ErrorCode.ERR_NoTypeDef, "Event1").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (4,39): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public event System.Action<int[]> Event1 = x => { }; Diagnostic(ErrorCode.ERR_NoTypeDef, "Event1").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); } [Fact] public void TestImplicitlyImplementEventModOpt_Custom() { var text = @" class C : ILErrors.InterfaceEvents { public event System.Action<int[]> Event1 { add { } remove { } } }"; CompileWithMissingReference(text).VerifyDiagnostics( // (4,56): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public event System.Action<int[]> Event1 { add { } remove { } } Diagnostic(ErrorCode.ERR_NoTypeDef, "remove").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (4,48): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public event System.Action<int[]> Event1 { add { } remove { } } Diagnostic(ErrorCode.ERR_NoTypeDef, "add").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); } [Fact] public void TestExplicitlyImplementEvent_Custom() //NB: can't explicitly implement with field-like { var text = @" class C : CSharpErrors.InterfaceEvents { event UnavailableDelegate CSharpErrors.InterfaceEvents.Event1 { add { } remove { } } event CSharpErrors.EventDelegate<UnavailableClass> CSharpErrors.InterfaceEvents.Event2 { add { } remove { } } event CSharpErrors.EventDelegate<UnavailableClass[]> CSharpErrors.InterfaceEvents.Event3 { add { } remove { } } }"; CompileWithMissingReference(text).VerifyDiagnostics( // (4,11): error CS0246: The type or namespace name 'UnavailableDelegate' could not be found (are you missing a using directive or an assembly reference?) // event UnavailableDelegate CSharpErrors.InterfaceEvents.Event1 { add { } remove { } } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableDelegate").WithArguments("UnavailableDelegate").WithLocation(4, 11), // (4,60): error CS0539: 'C.Event1' in explicit interface declaration is not a member of interface // event UnavailableDelegate CSharpErrors.InterfaceEvents.Event1 { add { } remove { } } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Event1").WithArguments("C.Event1").WithLocation(4, 60), // (5,38): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // event CSharpErrors.EventDelegate<UnavailableClass> CSharpErrors.InterfaceEvents.Event2 { add { } remove { } } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass").WithLocation(5, 38), // (5,85): error CS0539: 'C.Event2' in explicit interface declaration is not a member of interface // event CSharpErrors.EventDelegate<UnavailableClass> CSharpErrors.InterfaceEvents.Event2 { add { } remove { } } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Event2").WithArguments("C.Event2").WithLocation(5, 85), // (6,38): error CS0246: The type or namespace name 'UnavailableClass' could not be found (are you missing a using directive or an assembly reference?) // event CSharpErrors.EventDelegate<UnavailableClass[]> CSharpErrors.InterfaceEvents.Event3 { add { } remove { } } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnavailableClass").WithArguments("UnavailableClass").WithLocation(6, 38), // (6,87): error CS0539: 'C.Event3' in explicit interface declaration is not a member of interface // event CSharpErrors.EventDelegate<UnavailableClass[]> CSharpErrors.InterfaceEvents.Event3 { add { } remove { } } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Event3").WithArguments("C.Event3").WithLocation(6, 87), // (2,11): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // class C : CSharpErrors.InterfaceEvents Diagnostic(ErrorCode.ERR_NoTypeDef, "CSharpErrors.InterfaceEvents").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 11), // (2,11): error CS0012: The type 'UnavailableDelegate' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // class C : CSharpErrors.InterfaceEvents Diagnostic(ErrorCode.ERR_NoTypeDef, "CSharpErrors.InterfaceEvents").WithArguments("UnavailableDelegate", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 11), // (2,11): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // class C : CSharpErrors.InterfaceEvents Diagnostic(ErrorCode.ERR_NoTypeDef, "CSharpErrors.InterfaceEvents").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 11) ); } [Fact] public void TestExplicitlyImplementEventModOpt_Custom() //NB: can't explicitly implement with field-like { var text = @" class C : ILErrors.InterfaceEvents { event System.Action<int[]> ILErrors.InterfaceEvents.Event1 { add { } remove { } } }"; CompileWithMissingReference(text).VerifyDiagnostics( // (4,74): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // event System.Action<int[]> ILErrors.InterfaceEvents.Event1 { add { } remove { } } Diagnostic(ErrorCode.ERR_NoTypeDef, "remove").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (4,66): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // event System.Action<int[]> ILErrors.InterfaceEvents.Event1 { add { } remove { } } Diagnostic(ErrorCode.ERR_NoTypeDef, "add").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); } [Fact] public void TestEventAccess() { var text = @"class C { static void M(CSharpErrors.ClassEvents c, ILErrors.ClassEvents i) { c.Event1 += null; i.Event1 += null; } }"; CompileWithMissingReference(text).VerifyDiagnostics( // (5,11): error CS0012: The type 'UnavailableDelegate' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // c.Event1 += null; Diagnostic(ErrorCode.ERR_NoTypeDef, "Event1").WithArguments("UnavailableDelegate", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (6,11): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // i.Event1 += null; Diagnostic(ErrorCode.ERR_NoTypeDef, "Event1").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); } [Fact] public void TestDelegatesWithNoInvoke() { var text = @"class C { public static T goo<T>(DelegateWithoutInvoke.DelegateGenericFunctionWithoutInvoke<T> del) { return del(""goo""); // will show ERR_InvalidDelegateType instead of ERR_NoSuchMemberOrExtension } public static void Main() { DelegateWithoutInvoke.DelegateSubWithoutInvoke myDelegate1 = bar; myDelegate1.Invoke(""goo""); // will show an ERR_NoSuchMemberOrExtension DelegateWithoutInvoke.DelegateSubWithoutInvoke myDelegate2 = new DelegateWithoutInvoke.DelegateSubWithoutInvoke(myDelegate1); object myDelegate3 = new DelegateWithoutInvoke.DelegateSubWithoutInvoke(bar2); DelegateWithoutInvoke.DelegateSubWithoutInvoke myDelegate4 = x => System.Console.WriteLine(""Hello World""); object myDelegate6 = new DelegateWithoutInvoke.DelegateFunctionWithoutInvoke( x => ""Hello World""); } public static void bar(string p) { System.Console.WriteLine(""Hello World""); } public static void bar2(int p) { System.Console.WriteLine(""Hello World 2""); } }"; var delegatesWithoutInvokeReference = TestReferences.SymbolsTests.DelegateImplementation.DelegatesWithoutInvoke; CreateCompilation(text, new MetadataReference[] { delegatesWithoutInvokeReference }).VerifyDiagnostics( // (7,16): error CS7024: Delegate 'DelegateWithoutInvoke.DelegateGenericFunctionWithoutInvoke<T>' has no invoke method or an invoke method with a return type or parameter types that are not supported. // return del("goo"); // will show ERR_InvalidDelegateType instead of ERR_NoSuchMemberOrExtension Diagnostic(ErrorCode.ERR_InvalidDelegateType, @"del(""goo"")").WithArguments("DelegateWithoutInvoke.DelegateGenericFunctionWithoutInvoke<T>").WithLocation(7, 16), // (13,70): error CS7024: Delegate 'DelegateWithoutInvoke.DelegateSubWithoutInvoke' has no invoke method or an invoke method with a return type or parameter types that are not supported. // DelegateWithoutInvoke.DelegateSubWithoutInvoke myDelegate1 = bar; Diagnostic(ErrorCode.ERR_InvalidDelegateType, "bar").WithArguments("DelegateWithoutInvoke.DelegateSubWithoutInvoke").WithLocation(13, 70), // (14,21): error CS1061: 'DelegateWithoutInvoke.DelegateSubWithoutInvoke' does not contain a definition for 'Invoke' and no accessible extension method 'Invoke' accepting a first argument of type 'DelegateWithoutInvoke.DelegateSubWithoutInvoke' could be found (are you missing a using directive or an assembly reference?) // myDelegate1.Invoke("goo"); // will show an ERR_NoSuchMemberOrExtension Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Invoke").WithArguments("DelegateWithoutInvoke.DelegateSubWithoutInvoke", "Invoke").WithLocation(14, 21), // (15,70): error CS7024: Delegate 'DelegateWithoutInvoke.DelegateSubWithoutInvoke' has no invoke method or an invoke method with a return type or parameter types that are not supported. // DelegateWithoutInvoke.DelegateSubWithoutInvoke myDelegate2 = new DelegateWithoutInvoke.DelegateSubWithoutInvoke(myDelegate1); Diagnostic(ErrorCode.ERR_InvalidDelegateType, "new DelegateWithoutInvoke.DelegateSubWithoutInvoke(myDelegate1)").WithArguments("DelegateWithoutInvoke.DelegateSubWithoutInvoke").WithLocation(15, 70), // (16,30): error CS7024: Delegate 'DelegateWithoutInvoke.DelegateSubWithoutInvoke' has no invoke method or an invoke method with a return type or parameter types that are not supported. // object myDelegate3 = new DelegateWithoutInvoke.DelegateSubWithoutInvoke(bar2); Diagnostic(ErrorCode.ERR_InvalidDelegateType, "new DelegateWithoutInvoke.DelegateSubWithoutInvoke(bar2)").WithArguments("DelegateWithoutInvoke.DelegateSubWithoutInvoke").WithLocation(16, 30), // (17,70): error CS7024: Delegate 'DelegateWithoutInvoke.DelegateSubWithoutInvoke' has no invoke method or an invoke method with a return type or parameter types that are not supported. // DelegateWithoutInvoke.DelegateSubWithoutInvoke myDelegate4 = x => System.Console.WriteLine("Hello World"); Diagnostic(ErrorCode.ERR_InvalidDelegateType, @"x => System.Console.WriteLine(""Hello World"")").WithArguments("DelegateWithoutInvoke.DelegateSubWithoutInvoke").WithLocation(17, 70), // (18,87): error CS7024: Delegate 'DelegateWithoutInvoke.DelegateFunctionWithoutInvoke' has no invoke method or an invoke method with a return type or parameter types that are not supported. // object myDelegate6 = new DelegateWithoutInvoke.DelegateFunctionWithoutInvoke( x => "Hello World"); Diagnostic(ErrorCode.ERR_InvalidDelegateType, @"x => ""Hello World""").WithArguments("DelegateWithoutInvoke.DelegateFunctionWithoutInvoke").WithLocation(18, 87)); } [Fact] public void TestDelegatesWithUseSiteErrors() { var text = @"class C { public static T goo<T>(CSharpErrors.DelegateParameterType3<T> del) { return del.Invoke(""goo""); } public static void Main() { CSharpErrors.DelegateReturnType1 myDelegate1 = bar; myDelegate1(""goo""); CSharpErrors.DelegateReturnType1 myDelegate2 = new CSharpErrors.DelegateReturnType1(myDelegate1); object myDelegate3 = new CSharpErrors.DelegateReturnType1(bar); CSharpErrors.DelegateReturnType1 myDelegate4 = x => System.Console.WriteLine(""Hello World""); object myDelegate6 = new CSharpErrors.DelegateReturnType1( x => ""Hello World""); } public static void bar(string p) { System.Console.WriteLine(""Hello World""); } public static void bar2(int p) { System.Console.WriteLine(""Hello World 2""); } }"; var csharpAssemblyReference = TestReferences.SymbolsTests.UseSiteErrors.CSharp; var ilAssemblyReference = TestReferences.SymbolsTests.UseSiteErrors.IL; CreateCompilation(text, new MetadataReference[] { csharpAssemblyReference, ilAssemblyReference }).VerifyDiagnostics( // (7,16): error CS0012: The type 'UnavailableClass<>' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // return del.Invoke("goo"); Diagnostic(ErrorCode.ERR_NoTypeDef, "del.Invoke").WithArguments("UnavailableClass<>", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 16), // (13,56): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // CSharpErrors.DelegateReturnType1 myDelegate1 = bar; Diagnostic(ErrorCode.ERR_NoTypeDef, "bar").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(13, 56), // (14,9): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // myDelegate1("goo"); Diagnostic(ErrorCode.ERR_NoTypeDef, @"myDelegate1(""goo"")").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(14, 9), // (15,56): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // CSharpErrors.DelegateReturnType1 myDelegate2 = new CSharpErrors.DelegateReturnType1(myDelegate1); Diagnostic(ErrorCode.ERR_NoTypeDef, "new CSharpErrors.DelegateReturnType1(myDelegate1)").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(15, 56), // (16,30): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // object myDelegate3 = new CSharpErrors.DelegateReturnType1(bar); Diagnostic(ErrorCode.ERR_NoTypeDef, "new CSharpErrors.DelegateReturnType1(bar)").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(16, 30), // (17,56): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // CSharpErrors.DelegateReturnType1 myDelegate4 = x => System.Console.WriteLine("Hello World"); Diagnostic(ErrorCode.ERR_NoTypeDef, @"x => System.Console.WriteLine(""Hello World"")").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(17, 56), // (18,68): error CS0012: The type 'UnavailableClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // object myDelegate6 = new CSharpErrors.DelegateReturnType1( x => "Hello World"); Diagnostic(ErrorCode.ERR_NoTypeDef, @"x => ""Hello World""").WithArguments("UnavailableClass", "Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(18, 68)); } [Fact, WorkItem(531090, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531090")] public void Constructor() { string srcLib1 = @" using System; public sealed class A { public A(int a, Func<string, string> example) {} public A(Func<string, string> example) {} } "; var lib1 = CreateEmptyCompilation( new[] { Parse(srcLib1) }, new[] { TestMetadata.Net20.mscorlib, TestMetadata.Net35.SystemCore }, TestOptions.ReleaseDll.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default)); string srcLib2 = @" class Program { static void Main() { new A(x => x); } } "; var lib2 = CreateEmptyCompilation( new[] { Parse(srcLib2) }, new[] { MscorlibRef, new CSharpCompilationReference(lib1) }, TestOptions.ReleaseDll.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default)); lib2.VerifyDiagnostics( // (6,13): error CS0012: The type 'System.Func<,>' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. // new A(x => x); Diagnostic(ErrorCode.ERR_NoTypeDef, "A").WithArguments("System.Func<,>", "System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")); } [Fact, WorkItem(530974, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530974")] public void SynthesizedInterfaceImplementation() { var xSource = @" public class X {} "; var xRef = CreateCompilation(xSource, assemblyName: "Test").EmitToImageReference(); var libSource = @" public interface I { void Goo(X a); } public class C { public void Goo(X a) { } } "; var lib = CreateCompilation(libSource, new[] { xRef }, assemblyName: "Test"); var mainSource = @" class B : C, I { } "; var main = CreateCompilation(mainSource, new[] { new CSharpCompilationReference(lib) }, assemblyName: "Main"); main.VerifyDiagnostics( // (2,7): error CS7068: Reference to type 'X' claims it is defined in this assembly, but it is not defined in source or any added modules // class B : C, I { } Diagnostic(ErrorCode.ERR_MissingTypeInSource, "B").WithArguments("X")); } [Fact, WorkItem(530974, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530974")] public void NoSynthesizedInterfaceImplementation() { var xSource = @" public class X {} "; var xRef = CreateCompilation(xSource, assemblyName: "X").EmitToImageReference(); var libSource = @" public interface I { void Goo(X a); } public class C { public virtual void Goo(X a) { } } "; var lib = CreateCompilation(libSource, new[] { xRef }, assemblyName: "Lib"); var mainSource = @" class B : C, I { } "; var main = CreateCompilation(mainSource, new[] { new CSharpCompilationReference(lib) }, assemblyName: "Main"); main.VerifyEmitDiagnostics(); } [Fact, WorkItem(530974, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530974")] public void SynthesizedInterfaceImplementation_Indexer() { var xSource = @" public class X {} "; var xRef = CreateCompilation(xSource, assemblyName: "X").EmitToImageReference(); var libSource = @" public interface I { int this[X a] { get; set; } } public class C { public int this[X a] { get { return 1; } set { } } } "; var lib = CreateCompilation(libSource, new[] { xRef }, assemblyName: "Lib"); var mainSource = @" class B : C, I { } "; var main = CreateCompilation(mainSource, new[] { new CSharpCompilationReference(lib) }, assemblyName: "Main"); main.VerifyDiagnostics( // (2,7): error CS0012: The type 'X' is defined in an assembly that is not referenced. You must add a reference to assembly 'X, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // class B : C, I { } Diagnostic(ErrorCode.ERR_NoTypeDef, "B").WithArguments("X", "X, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (2,7): error CS0012: The type 'X' is defined in an assembly that is not referenced. You must add a reference to assembly 'X, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // class B : C, I { } Diagnostic(ErrorCode.ERR_NoTypeDef, "B").WithArguments("X", "X, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); } [Fact, WorkItem(530974, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530974")] public void SynthesizedInterfaceImplementation_ModOpt() { var unavailableRef = TestReferences.SymbolsTests.UseSiteErrors.Unavailable; var ilRef = TestReferences.SymbolsTests.UseSiteErrors.IL; var mainSource = @" class B : ILErrors.ClassEventsNonVirtual, ILErrors.InterfaceEvents { } "; var main = CreateCompilation(mainSource, new[] { ilRef, unavailableRef }); CompileAndVerify(main); } [Fact, WorkItem(530974, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530974")] public void NoSynthesizedInterfaceImplementation_ModOpt() { var unavailableRef = TestReferences.SymbolsTests.UseSiteErrors.Unavailable; var ilRef = TestReferences.SymbolsTests.UseSiteErrors.IL; var mainSource = @" class B : ILErrors.ClassEvents, ILErrors.InterfaceEvents { } "; var main = CreateCompilation(mainSource, new[] { ilRef, unavailableRef }); CompileAndVerify(main); } [Fact, WorkItem(530974, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530974")] public void SynthesizedInterfaceImplementation_ModReq() { var unavailableRef = TestReferences.SymbolsTests.UseSiteErrors.Unavailable; var ilRef = TestReferences.SymbolsTests.UseSiteErrors.IL; var mainSource = @" class B : ILErrors.ModReqClassEventsNonVirtual, ILErrors.ModReqInterfaceEvents { } "; var main = CreateCompilation(mainSource, new[] { ilRef, unavailableRef }); main.VerifyDiagnostics( // (2,7): error CS0570: 'ModReqInterfaceEvents.Event1.remove' is not supported by the language // class B : ILErrors.ModReqClassEventsNonVirtual, ILErrors.ModReqInterfaceEvents { } Diagnostic(ErrorCode.ERR_BindToBogus, "B").WithArguments("ILErrors.ModReqInterfaceEvents.Event1.remove").WithLocation(2, 7), // (2,7): error CS0570: 'ModReqInterfaceEvents.Event1.add' is not supported by the language // class B : ILErrors.ModReqClassEventsNonVirtual, ILErrors.ModReqInterfaceEvents { } Diagnostic(ErrorCode.ERR_BindToBogus, "B").WithArguments("ILErrors.ModReqInterfaceEvents.Event1.add").WithLocation(2, 7) ); } [Fact] public void CompilerGeneratedAttributeNotRequired() { var text = @"class C { public int AProperty { get; set; } }"; var compilation = CreateEmptyCompilation(text).VerifyDiagnostics( // (1,7): error CS0518: Predefined type 'System.Object' is not defined or imported // class C Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "C").WithArguments("System.Object"), // (3,11): error CS0518: Predefined type 'System.Int32' is not defined or imported // public int AProperty { get; set; } Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "int").WithArguments("System.Int32"), // (3,32): error CS0518: Predefined type 'System.Void' is not defined or imported // public int AProperty { get; set; } Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "set;").WithArguments("System.Void"), // (1,7): error CS1729: 'object' does not contain a constructor that takes 0 arguments // class C Diagnostic(ErrorCode.ERR_BadCtorArgCount, "C").WithArguments("object", "0")); foreach (var diag in compilation.GetDiagnostics()) { Assert.DoesNotContain("System.Runtime.CompilerServices.CompilerGeneratedAttribute", diag.GetMessage(), StringComparison.Ordinal); } } [Fact] public void UseSiteErrorsForSwitchSubsumption() { var baseSource = @"public class Base {}"; var baseLib = CreateCompilation(baseSource, assemblyName: "BaseAssembly"); var derivedSource = @"public class Derived : Base {}"; var derivedLib = CreateCompilation(derivedSource, assemblyName: "DerivedAssembly", references: new[] { new CSharpCompilationReference(baseLib) }); var programSource = @" class Program { public static void Main(string[] args) { object o = args; switch (o) { case string s: break; case Derived d: break; } } } "; CreateCompilation(programSource, references: new[] { new CSharpCompilationReference(derivedLib) }).VerifyDiagnostics( // (9,18): error CS0012: The type 'Base' is defined in an assembly that is not referenced. You must add a reference to assembly 'BaseAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // case string s: break; Diagnostic(ErrorCode.ERR_NoTypeDef, "string s").WithArguments("Base", "BaseAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(9, 18) ); } #region Attributes for unsafe code /// <summary> /// Simple test to verify that the infrastructure for the other UnsafeAttributes_* tests works correctly. /// </summary> [Fact] public void UnsafeAttributes_NoErrors() { var text = unsafeAttributeSystemTypes + @" namespace System.Security { public class UnverifiableCodeAttribute : Attribute { } namespace Permissions { public enum SecurityAction { RequestMinimum } public class CodeAccessSecurityAttribute : Attribute { public CodeAccessSecurityAttribute(SecurityAction action) { } } public class SecurityPermissionAttribute : CodeAccessSecurityAttribute { public SecurityPermissionAttribute(SecurityAction action) : base(action) { } public bool SkipVerification { get; set; } } } } "; CompileUnsafeAttributesAndCheckDiagnostics(text, false, // (19,21): error CS0518: Predefined type 'System.Int32' is not defined or imported // public enum SecurityAction Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "SecurityAction").WithArguments("System.Int32")); CompileUnsafeAttributesAndCheckDiagnostics(text, true, // (19,21): error CS0518: Predefined type 'System.Int32' is not defined or imported // public enum SecurityAction Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "SecurityAction").WithArguments("System.Int32")); } /// <summary> /// If the attribute type is missing, just skip emitting the attributes. /// No diagnostics. /// </summary> [Fact] public void UnsafeAttributes_MissingUnverifiableCodeAttribute() { var text = unsafeAttributeSystemTypes + @" namespace System.Security { public class UnverifiableCodeAttribute : Attribute { } namespace Permissions { public enum SecurityAction { RequestMinimum } public class CodeAccessSecurityAttribute : Attribute { public CodeAccessSecurityAttribute(SecurityAction action) { } } public class SecurityPermissionAttribute : CodeAccessSecurityAttribute { public SecurityPermissionAttribute(SecurityAction action) : base(action) { } public bool SkipVerification { get; set; } } } } "; CompileUnsafeAttributesAndCheckDiagnostics(text, false, // (19,21): error CS0518: Predefined type 'System.Int32' is not defined or imported // public enum SecurityAction Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "SecurityAction").WithArguments("System.Int32")); CompileUnsafeAttributesAndCheckDiagnostics(text, true, // (19,21): error CS0518: Predefined type 'System.Int32' is not defined or imported // public enum SecurityAction Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "SecurityAction").WithArguments("System.Int32")); } /// <summary> /// If the attribute type is missing, just skip emitting the attributes. /// No diagnostics. /// </summary> [Fact] public void UnsafeAttributes_MissingSecurityPermissionAttribute() { var text = unsafeAttributeSystemTypes + @" namespace System.Security { public class UnverifiableCodeAttribute : Attribute { } namespace Permissions { public enum SecurityAction { RequestMinimum } } } "; CompileUnsafeAttributesAndCheckDiagnostics(text, false, // (19,21): error CS0518: Predefined type 'System.Int32' is not defined or imported // public enum SecurityAction Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "SecurityAction").WithArguments("System.Int32")); CompileUnsafeAttributesAndCheckDiagnostics(text, true, // (19,21): error CS0518: Predefined type 'System.Int32' is not defined or imported // public enum SecurityAction Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "SecurityAction").WithArguments("System.Int32")); } /// <summary> /// If the enum type is missing, just skip emitting the attributes. /// No diagnostics. /// </summary> [Fact] public void UnsafeAttributes_MissingSecurityAction() { var text = unsafeAttributeSystemTypes + @" namespace System.Security { public class UnverifiableCodeAttribute : Attribute { } namespace Permissions { public class CodeAccessSecurityAttribute : Attribute { } public class SecurityPermissionAttribute : CodeAccessSecurityAttribute { public bool SkipVerification { get; set; } } } } "; CompileUnsafeAttributesAndCheckDiagnostics(text, false); CompileUnsafeAttributesAndCheckDiagnostics(text, true); } /// <summary> /// If the attribute constructor is missing, report a use site error. /// </summary> [Fact] public void UnsafeAttributes_MissingUnverifiableCodeAttributeCtorMissing() { var text = unsafeAttributeSystemTypes + @" namespace System.Security { public class UnverifiableCodeAttribute : Attribute { public UnverifiableCodeAttribute(object o1, object o2) { } //wrong signature, won't be found } namespace Permissions { public enum SecurityAction { RequestMinimum } public class CodeAccessSecurityAttribute : Attribute { public CodeAccessSecurityAttribute(SecurityAction action) { } } public class SecurityPermissionAttribute : CodeAccessSecurityAttribute { public SecurityPermissionAttribute(SecurityAction action) : base(action) { } public bool SkipVerification { get; set; } } } } "; CompileUnsafeAttributesAndCheckDiagnostics(text, false, // error CS0656: Missing compiler required member 'System.Security.UnverifiableCodeAttribute..ctor' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.Security.UnverifiableCodeAttribute", ".ctor"), // (22,21): error CS0518: Predefined type 'System.Int32' is not defined or imported // public enum SecurityAction Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "SecurityAction").WithArguments("System.Int32")); CompileUnsafeAttributesAndCheckDiagnostics(text, true, // error CS0656: Missing compiler required member 'System.Security.UnverifiableCodeAttribute..ctor' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.Security.UnverifiableCodeAttribute", ".ctor"), // (22,21): error CS0518: Predefined type 'System.Int32' is not defined or imported // public enum SecurityAction Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "SecurityAction").WithArguments("System.Int32")); } /// <summary> /// If the attribute constructor is missing, report a use site error. /// </summary> [Fact] public void UnsafeAttributes_SecurityPermissionAttributeCtorMissing() { var text = unsafeAttributeSystemTypes + @" namespace System.Security { public class UnverifiableCodeAttribute : Attribute { } namespace Permissions { public enum SecurityAction { RequestMinimum } public class CodeAccessSecurityAttribute : Attribute { public CodeAccessSecurityAttribute(SecurityAction action) { } } public class SecurityPermissionAttribute : CodeAccessSecurityAttribute { public SecurityPermissionAttribute(SecurityAction action, object o) //extra parameter will fail to match well-known signature : base(action) { } public bool SkipVerification { get; set; } } } } "; CompileUnsafeAttributesAndCheckDiagnostics(text, false, // error CS0656: Missing compiler required member 'System.Security.Permissions.SecurityPermissionAttribute..ctor' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.Security.Permissions.SecurityPermissionAttribute", ".ctor"), // (21,21): error CS0518: Predefined type 'System.Int32' is not defined or imported // public enum SecurityAction Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "SecurityAction").WithArguments("System.Int32")); CompileUnsafeAttributesAndCheckDiagnostics(text, true, // error CS0656: Missing compiler required member 'System.Security.Permissions.SecurityPermissionAttribute..ctor' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.Security.Permissions.SecurityPermissionAttribute", ".ctor"), // (21,21): error CS0518: Predefined type 'System.Int32' is not defined or imported // public enum SecurityAction Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "SecurityAction").WithArguments("System.Int32")); } /// <summary> /// If the attribute property is missing, report a use site error. /// </summary> [Fact] public void UnsafeAttributes_SecurityPermissionAttributePropertyMissing() { var text = unsafeAttributeSystemTypes + @" namespace System.Security { public class UnverifiableCodeAttribute : Attribute { } namespace Permissions { public enum SecurityAction { RequestMinimum } public class CodeAccessSecurityAttribute : Attribute { public CodeAccessSecurityAttribute(SecurityAction action) { } } public class SecurityPermissionAttribute : CodeAccessSecurityAttribute { public SecurityPermissionAttribute(SecurityAction action) : base(action) { } } } } "; CompileUnsafeAttributesAndCheckDiagnostics(text, false, // error CS0656: Missing compiler required member 'System.Security.Permissions.SecurityPermissionAttribute.SkipVerification' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.Security.Permissions.SecurityPermissionAttribute", "SkipVerification"), // (21,21): error CS0518: Predefined type 'System.Int32' is not defined or imported // public enum SecurityAction Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "SecurityAction").WithArguments("System.Int32")); CompileUnsafeAttributesAndCheckDiagnostics(text, true, // error CS0656: Missing compiler required member 'System.Security.Permissions.SecurityPermissionAttribute.SkipVerification' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.Security.Permissions.SecurityPermissionAttribute", "SkipVerification"), // (21,21): error CS0518: Predefined type 'System.Int32' is not defined or imported // public enum SecurityAction Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "SecurityAction").WithArguments("System.Int32")); } [WorkItem(708169, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/708169")] [Fact] public void OverloadResolutionWithUseSiteErrors() { var missingSource = @" public class Missing { } "; var libSource = @" public class Methods { public static void M1(int x) { } public static void M1(Missing x) { } public static void M2(Missing x) { } public static void M2(int x) { } } public class Indexer1 { public int this[int x] { get { return 0; } } public int this[Missing x] { get { return 0; } } } public class Indexer2 { public int this[Missing x] { get { return 0; } } public int this[int x] { get { return 0; } } } public class Constructor1 { public Constructor1(int x) { } public Constructor1(Missing x) { } } public class Constructor2 { public Constructor2(Missing x) { } public Constructor2(int x) { } } "; var testSource = @" using System; class C { static void Main() { var c1 = new Constructor1(1); var c2 = new Constructor2(2); Methods.M1(1); Methods.M2(2); Action<int> a1 = Methods.M1; Action<int> a2 = Methods.M2; var i1 = new Indexer1()[1]; var i2 = new Indexer2()[2]; } } "; var missingRef = CreateCompilation(missingSource, assemblyName: "Missing").EmitToImageReference(); var libRef = CreateCompilation(libSource, new[] { missingRef }).EmitToImageReference(); CreateCompilation(testSource, new[] { libRef /* and not missingRef */ }).VerifyDiagnostics( // (8,22): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // var c1 = new Constructor1(1); Diagnostic(ErrorCode.ERR_NoTypeDef, "Constructor1").WithArguments("Missing", "Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (9,22): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // var c2 = new Constructor2(2); Diagnostic(ErrorCode.ERR_NoTypeDef, "Constructor2").WithArguments("Missing", "Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (9,9): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // Methods.M1(1); Diagnostic(ErrorCode.ERR_NoTypeDef, "Methods.M1").WithArguments("Missing", "Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (10,9): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // Methods.M2(2); Diagnostic(ErrorCode.ERR_NoTypeDef, "Methods.M2").WithArguments("Missing", "Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (14,26): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // Action<int> a1 = Methods.M1; Diagnostic(ErrorCode.ERR_NoTypeDef, "Methods.M1").WithArguments("Missing", "Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (15,26): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // Action<int> a2 = Methods.M2; Diagnostic(ErrorCode.ERR_NoTypeDef, "Methods.M2").WithArguments("Missing", "Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (17,18): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // var i1 = new Indexer1()[1]; Diagnostic(ErrorCode.ERR_NoTypeDef, "new Indexer1()[1]").WithArguments("Missing", "Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (18,18): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // var i2 = new Indexer2()[2]; Diagnostic(ErrorCode.ERR_NoTypeDef, "new Indexer2()[2]").WithArguments("Missing", "Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); } [WorkItem(708169, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/708169")] [Fact] public void OverloadResolutionWithUseSiteErrors_LessDerived() { var missingSource = @" public class Missing { } "; var libSource = @" public class Base { public int M(int x) { return 0; } public int M(Missing x) { return 0; } public int this[int x] { get { return 0; } } public int this[Missing x] { get { return 0; } } } "; var testSource = @" class Derived : Base { static void Main() { var d = new Derived(); int i; i = d.M(1); i = d.M(""A""); i = d[1]; i = d[""A""]; } public int M(string x) { return 0; } public int this[string x] { get { return 0; } } } "; var missingRef = CreateCompilation(missingSource, assemblyName: "Missing").EmitToImageReference(); var libRef = CreateCompilation(libSource, new[] { missingRef }).EmitToImageReference(); CreateCompilation(testSource, new[] { libRef, missingRef }).VerifyDiagnostics(); // NOTE: No errors reported when the Derived member wins. CreateCompilation(testSource, new[] { libRef /* and not missingRef */ }).VerifyDiagnostics( // (9,13): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // i = d.M(1); Diagnostic(ErrorCode.ERR_NoTypeDef, "d.M").WithArguments("Missing", "Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (12,13): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // i = d[1]; Diagnostic(ErrorCode.ERR_NoTypeDef, "d[1]").WithArguments("Missing", "Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); } [WorkItem(708169, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/708169")] [Fact] public void OverloadResolutionWithUseSiteErrors_NoCorrespondingParameter() { var missingSource = @" public class Missing { } "; var libSource = @" public class C { public C(string x, int y = 1) { } public C(Missing x) { } public int M(string x, int y = 1) { return 0; } public int M(Missing x) { return 0; } public int this[string x, int y = 1] { get { return 0; } } public int this[Missing x] { get { return 0; } } } "; var testSource = @" class Test { static void Main() { C c; int i; c = new C(null, 1); // Fine c = new C(""A""); // Error i = c.M(null, 1); // Fine i = c.M(""A""); // Error i = c[null, 1]; // Fine i = c[""A""]; // Error } } "; var missingRef = CreateCompilation(missingSource, assemblyName: "Missing").EmitToImageReference(); var libRef = CreateCompilation(libSource, new[] { missingRef }).EmitToImageReference(); CreateCompilation(testSource, new[] { libRef, missingRef }).VerifyDiagnostics(); CreateCompilation(testSource, new[] { libRef /* and not missingRef */ }).VerifyDiagnostics( // (10,17): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // c = new C("A"); // Error Diagnostic(ErrorCode.ERR_NoTypeDef, "C").WithArguments("Missing", "Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (13,13): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // i = c.M("A"); // Error Diagnostic(ErrorCode.ERR_NoTypeDef, "c.M").WithArguments("Missing", "Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (16,13): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // i = c["A"]; // Error Diagnostic(ErrorCode.ERR_NoTypeDef, @"c[""A""]").WithArguments("Missing", "Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); } [WorkItem(708169, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/708169")] [Fact] public void OverloadResolutionWithUseSiteErrors_NameUsedForPositional() { var missingSource = @" public class Missing { } "; var libSource = @" public class C { public C(string x, string y) { } public C(Missing y, string x) { } public int M(string x, string y) { return 0; } public int M(Missing y, string x) { return 0; } public int this[string x, string y] { get { return 0; } } public int this[Missing y, string x] { get { return 0; } } } "; var testSource = @" class Test { static void Main() { C c; int i; c = new C(""A"", y: null); // Fine c = new C(""A"", null); // Error i = c.M(""A"", y: null); // Fine i = c.M(""A"", null); // Error i = c[""A"", y: null]; // Fine i = c[""A"", null]; // Error } } "; var missingRef = CreateCompilation(missingSource, assemblyName: "Missing").EmitToImageReference(); var libRef = CreateCompilation(libSource, new[] { missingRef }).EmitToImageReference(); CreateCompilation(testSource, new[] { libRef, missingRef }).VerifyDiagnostics(); CreateCompilation(testSource, new[] { libRef /* and not missingRef */ }).VerifyDiagnostics( // (10,17): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // c = new C("A", null); // Error Diagnostic(ErrorCode.ERR_NoTypeDef, "C").WithArguments("Missing", "Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (13,13): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // i = c.M("A", null); // Error Diagnostic(ErrorCode.ERR_NoTypeDef, "c.M").WithArguments("Missing", "Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (16,13): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // i = c["A", null]; // Error Diagnostic(ErrorCode.ERR_NoTypeDef, @"c[""A"", null]").WithArguments("Missing", "Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); } [WorkItem(708169, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/708169")] [Fact] public void OverloadResolutionWithUseSiteErrors_RequiredParameterMissing() { var missingSource = @" public class Missing { } "; var libSource = @" public class C { public C(string x, object y = null) { } public C(Missing x, string y) { } public int M(string x, object y = null) { return 0; } public int M(Missing x, string y) { return 0; } public int this[string x, object y = null] { get { return 0; } } public int this[Missing x, string y] { get { return 0; } } } "; var testSource = @" class Test { static void Main() { C c; int i; c = new C(null); // Fine c = new C(null, ""A""); // Error i = c.M(null); // Fine i = c.M(null, ""A""); // Error i = c[null]; // Fine i = c[null, ""A""]; // Error } } "; var missingRef = CreateCompilation(missingSource, assemblyName: "Missing").EmitToImageReference(); var libRef = CreateCompilation(libSource, new[] { missingRef }).EmitToImageReference(); CreateCompilation(testSource, new[] { libRef, missingRef }).VerifyDiagnostics(); CreateCompilation(testSource, new[] { libRef /* and not missingRef */ }).VerifyDiagnostics( // (10,17): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // c = new C(null, "A"); // Error Diagnostic(ErrorCode.ERR_NoTypeDef, "C").WithArguments("Missing", "Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (13,13): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // i = c.M(null, "A"); // Error Diagnostic(ErrorCode.ERR_NoTypeDef, "c.M").WithArguments("Missing", "Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (16,13): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // i = c[null, "A"]; // Error Diagnostic(ErrorCode.ERR_NoTypeDef, @"c[null, ""A""]").WithArguments("Missing", "Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); } [Fact] public void OverloadResolutionWithUseSiteErrors_WithParamsArguments_ReturnsUseSiteErrors() { var missingSource = @" public class Missing { } "; var libSource = @" public class C { public static Missing GetMissing(params int[] args) { return null; } public static void SetMissing(params Missing[] args) { } public static Missing GetMissing(string firstArgument, params int[] args) { return null; } public static void SetMissing(string firstArgument, params Missing[] args) { } } "; var testSource = @" class Test { static void Main() { C.GetMissing(); C.GetMissing(1, 1); C.SetMissing(); C.GetMissing(string.Empty); C.GetMissing(string.Empty, 1, 1); C.SetMissing(string.Empty); } } "; var missingRef = CreateCompilation(missingSource, assemblyName: "Missing").EmitToImageReference(); var libRef = CreateCompilation(libSource, new[] { missingRef }).EmitToImageReference(); CreateCompilation(testSource, new[] { libRef, missingRef }).VerifyDiagnostics(); var getMissingDiagnostic = Diagnostic(ErrorCode.ERR_NoTypeDef, @"C.GetMissing").WithArguments("Missing", "Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"); var setMissingDiagnostic = Diagnostic(ErrorCode.ERR_NoTypeDef, @"C.SetMissing").WithArguments("Missing", "Missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"); CreateCompilation(testSource, new[] { libRef /* and not missingRef */ }).VerifyDiagnostics( getMissingDiagnostic, getMissingDiagnostic, setMissingDiagnostic, getMissingDiagnostic, getMissingDiagnostic, setMissingDiagnostic); } [WorkItem(708169, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/708169")] [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void OverloadResolutionWithUnsupportedMetadata_UnsupportedMetadata_SupportedExists() { var il = @" .class public auto ansi beforefieldinit Methods extends [mscorlib]System.Object { .method public hidebysig static void M(int32 x) cil managed { ret } .method public hidebysig static void M(string modreq(int16) x) cil managed { ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } // end of class Methods .class public auto ansi beforefieldinit Indexers extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('Item')} .method public hidebysig specialname instance int32 get_Item(int32 x) cil managed { ldc.i4.0 ret } .method public hidebysig specialname instance int32 get_Item(string modreq(int16) x) cil managed { ldc.i4.0 ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .property instance int32 Item(int32) { .get instance int32 Indexers::get_Item(int32) } .property instance int32 Item(string modreq(int16)) { .get instance int32 Indexers::get_Item(string modreq(int16)) } } // end of class Indexers .class public auto ansi beforefieldinit Constructors extends [mscorlib]System.Object { .method public hidebysig specialname rtspecialname instance void .ctor(int32 x) cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .method public hidebysig specialname rtspecialname instance void .ctor(string modreq(int16) x) cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } // end of class Constructors "; var source = @" using System; class C { static void Main() { var c1 = new Constructors(1); var c2 = new Constructors(null); Methods.M(1); Methods.M(null); Action<int> a1 = Methods.M; Action<string> a2 = Methods.M; var i1 = new Indexers()[1]; var i2 = new Indexers()[null]; } } "; CreateCompilationWithILAndMscorlib40(source, il).VerifyDiagnostics( // (9,35): error CS1503: Argument 1: cannot convert from '<null>' to 'int' // var c2 = new Constructors(null); Diagnostic(ErrorCode.ERR_BadArgType, "null").WithArguments("1", "<null>", "int"), // (12,19): error CS1503: Argument 1: cannot convert from '<null>' to 'int' // Methods.M(null); Diagnostic(ErrorCode.ERR_BadArgType, "null").WithArguments("1", "<null>", "int"), // (15,37): error CS0123: No overload for 'M' matches delegate 'System.Action<string>' // Action<string> a2 = Methods.M; Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "M").WithArguments("M", "System.Action<string>"), // (18,33): error CS1503: Argument 1: cannot convert from '<null>' to 'int' // var i2 = new Indexers()[null]; Diagnostic(ErrorCode.ERR_BadArgType, "null").WithArguments("1", "<null>", "int")); } [WorkItem(708169, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/708169")] [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void OverloadResolutionWithUnsupportedMetadata_UnsupportedMetadata_SupportedDoesNotExist() { var il = @" .class public auto ansi beforefieldinit Methods extends [mscorlib]System.Object { .method public hidebysig static void M(string modreq(int16) x) cil managed { ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } // end of class Methods .class public auto ansi beforefieldinit Indexers extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('Item')} .method public hidebysig specialname instance int32 get_Item(string modreq(int16) x) cil managed { ldc.i4.0 ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .property instance int32 Item(string modreq(int16)) { .get instance int32 Indexers::get_Item(string modreq(int16)) } } // end of class Indexers .class public auto ansi beforefieldinit Constructors extends [mscorlib]System.Object { .method public hidebysig specialname rtspecialname instance void .ctor(string modreq(int16) x) cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } // end of class Constructors "; var source = @" using System; class C { static void Main() { var c2 = new Constructors(null); Methods.M(null); Action<string> a2 = Methods.M; var i2 = new Indexers()[null]; } } "; CreateCompilationWithILAndMscorlib40(source, il).VerifyDiagnostics( // (8,22): error CS0570: 'Constructors.Constructors(string)' is not supported by the language // var c2 = new Constructors(null); Diagnostic(ErrorCode.ERR_BindToBogus, "Constructors").WithArguments("Constructors.Constructors(string)").WithLocation(8, 22), // (10,17): error CS0570: 'Methods.M(string)' is not supported by the language // Methods.M(null); Diagnostic(ErrorCode.ERR_BindToBogus, "M").WithArguments("Methods.M(string)").WithLocation(10, 17), // (12,29): error CS0570: 'Methods.M(string)' is not supported by the language // Action<string> a2 = Methods.M; Diagnostic(ErrorCode.ERR_BindToBogus, "Methods.M").WithArguments("Methods.M(string)").WithLocation(12, 29), // (14,18): error CS1546: Property, indexer, or event 'Indexers.this[string]' is not supported by the language; try directly calling accessor method 'Indexers.get_Item(string)' // var i2 = new Indexers()[null]; Diagnostic(ErrorCode.ERR_BindToBogusProp1, "new Indexers()[null]").WithArguments("Indexers.this[string]", "Indexers.get_Item(string)").WithLocation(14, 18)); } [WorkItem(939928, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/939928")] [WorkItem(132, "CodePlex")] [Fact] public void MissingBaseTypeForCatch() { var source1 = @" using System; public class GeneralException : Exception {}"; CSharpCompilation comp1 = CreateCompilation(source1, assemblyName: "Base"); var source2 = @" public class SpecificException : GeneralException {}"; CSharpCompilation comp2 = CreateCompilation(source2, new MetadataReference[] { new CSharpCompilationReference(comp1) }); var source3 = @" class Test { static void Main(string[] args) { try { SpecificException e = null; throw e; } catch (SpecificException) { } } }"; CSharpCompilation comp3 = CreateCompilation(source3, new MetadataReference[] { new CSharpCompilationReference(comp2) }); DiagnosticDescription[] expected = { // (9,23): error CS0012: The type 'GeneralException' is defined in an assembly that is not referenced. You must add a reference to assembly 'Base, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // throw e; Diagnostic(ErrorCode.ERR_NoTypeDef, "e").WithArguments("GeneralException", "Base, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(9, 23), // (9,23): error CS0029: Cannot implicitly convert type 'SpecificException' to 'System.Exception' // throw e; Diagnostic(ErrorCode.ERR_NoImplicitConv, "e").WithArguments("SpecificException", "System.Exception").WithLocation(9, 23), // (11,20): error CS0155: The type caught or thrown must be derived from System.Exception // catch (SpecificException) Diagnostic(ErrorCode.ERR_BadExceptionType, "SpecificException").WithLocation(11, 20), // (11,20): error CS0012: The type 'GeneralException' is defined in an assembly that is not referenced. You must add a reference to assembly 'Base, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // catch (SpecificException) Diagnostic(ErrorCode.ERR_NoTypeDef, "SpecificException").WithArguments("GeneralException", "Base, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(11, 20) }; comp3.VerifyDiagnostics(expected); comp3 = CreateCompilation(source3, new MetadataReference[] { comp2.EmitToImageReference() }); comp3.VerifyDiagnostics(expected); } /// <summary> /// Trivial definitions of special types that will be required for testing use site errors in /// the attributes emitted for unsafe assemblies. /// </summary> private const string unsafeAttributeSystemTypes = @" namespace System { public class Object { } public class ValueType { } public class Enum { } // Diagnostic if this extends ValueType public struct Boolean { } public struct Void { } public class Attribute { } } "; /// <summary> /// Compile without corlib, and then verify semantic diagnostics, emit-metadata diagnostics, and emit diagnostics. /// </summary> private static void CompileUnsafeAttributesAndCheckDiagnostics(string corLibText, bool moduleOnly, params DiagnosticDescription[] expectedDiagnostics) { CSharpCompilationOptions options = TestOptions.UnsafeReleaseDll; if (moduleOnly) { options = options.WithOutputKind(OutputKind.NetModule); } var compilation = CreateEmptyCompilation( new[] { Parse(corLibText) }, options: options); compilation.VerifyDiagnostics(expectedDiagnostics); } #endregion Attributes for unsafe code /// <summary> /// First, compile the provided source with all assemblies and confirm that there are no errors. /// Then, compile the provided source again without the unavailable assembly and return the result. /// </summary> private static CSharpCompilation CompileWithMissingReference(string source) { var unavailableAssemblyReference = TestReferences.SymbolsTests.UseSiteErrors.Unavailable; var csharpAssemblyReference = TestReferences.SymbolsTests.UseSiteErrors.CSharp; var ilAssemblyReference = TestReferences.SymbolsTests.UseSiteErrors.IL; var successfulCompilation = CreateCompilation(source, new MetadataReference[] { unavailableAssemblyReference, csharpAssemblyReference, ilAssemblyReference }); successfulCompilation.VerifyDiagnostics(); // No diagnostics when reference is present var failingCompilation = CreateCompilation(source, new MetadataReference[] { csharpAssemblyReference, ilAssemblyReference }); return failingCompilation; } [Fact] [WorkItem(14267, "https://github.com/dotnet/roslyn/issues/14267")] public void MissingTypeKindBasisTypes() { var source1 = @" public struct A {} public enum B {} public class C {} public delegate void D(); public interface I1 {} "; var compilation1 = CreateEmptyCompilation(source1, options: TestOptions.ReleaseDll, references: new[] { MinCorlibRef }); compilation1.VerifyEmitDiagnostics(); Assert.Equal(TypeKind.Struct, compilation1.GetTypeByMetadataName("A").TypeKind); Assert.Equal(TypeKind.Enum, compilation1.GetTypeByMetadataName("B").TypeKind); Assert.Equal(TypeKind.Class, compilation1.GetTypeByMetadataName("C").TypeKind); Assert.Equal(TypeKind.Delegate, compilation1.GetTypeByMetadataName("D").TypeKind); Assert.Equal(TypeKind.Interface, compilation1.GetTypeByMetadataName("I1").TypeKind); var source2 = @" interface I2 { I1 M(A a, B b, C c, D d); } "; var compilation2 = CreateEmptyCompilation(source2, options: TestOptions.ReleaseDll, references: new[] { compilation1.EmitToImageReference(), MinCorlibRef }); compilation2.VerifyEmitDiagnostics(); CompileAndVerify(compilation2); Assert.Equal(TypeKind.Struct, compilation2.GetTypeByMetadataName("A").TypeKind); Assert.Equal(TypeKind.Enum, compilation2.GetTypeByMetadataName("B").TypeKind); Assert.Equal(TypeKind.Class, compilation2.GetTypeByMetadataName("C").TypeKind); Assert.Equal(TypeKind.Delegate, compilation2.GetTypeByMetadataName("D").TypeKind); Assert.Equal(TypeKind.Interface, compilation2.GetTypeByMetadataName("I1").TypeKind); var compilation3 = CreateEmptyCompilation(source2, options: TestOptions.ReleaseDll, references: new[] { compilation1.ToMetadataReference(), MinCorlibRef }); compilation3.VerifyEmitDiagnostics(); CompileAndVerify(compilation3); Assert.Equal(TypeKind.Struct, compilation3.GetTypeByMetadataName("A").TypeKind); Assert.Equal(TypeKind.Enum, compilation3.GetTypeByMetadataName("B").TypeKind); Assert.Equal(TypeKind.Class, compilation3.GetTypeByMetadataName("C").TypeKind); Assert.Equal(TypeKind.Delegate, compilation3.GetTypeByMetadataName("D").TypeKind); Assert.Equal(TypeKind.Interface, compilation3.GetTypeByMetadataName("I1").TypeKind); var compilation4 = CreateEmptyCompilation(source2, options: TestOptions.ReleaseDll, references: new[] { compilation1.EmitToImageReference() }); compilation4.VerifyDiagnostics( // (4,10): error CS0012: The type 'ValueType' is defined in an assembly that is not referenced. You must add a reference to assembly 'mincorlib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2'. // I1 M(A a, B b, C c, D d); Diagnostic(ErrorCode.ERR_NoTypeDef, "A").WithArguments("System.ValueType", "mincorlib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2").WithLocation(4, 10), // (4,15): error CS0012: The type 'Enum' is defined in an assembly that is not referenced. You must add a reference to assembly 'mincorlib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2'. // I1 M(A a, B b, C c, D d); Diagnostic(ErrorCode.ERR_NoTypeDef, "B").WithArguments("System.Enum", "mincorlib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2").WithLocation(4, 15), // (4,25): error CS0012: The type 'MulticastDelegate' is defined in an assembly that is not referenced. You must add a reference to assembly 'mincorlib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2'. // I1 M(A a, B b, C c, D d); Diagnostic(ErrorCode.ERR_NoTypeDef, "D").WithArguments("System.MulticastDelegate", "mincorlib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2").WithLocation(4, 25) ); var a = compilation4.GetTypeByMetadataName("A"); var b = compilation4.GetTypeByMetadataName("B"); var c = compilation4.GetTypeByMetadataName("C"); var d = compilation4.GetTypeByMetadataName("D"); var i1 = compilation4.GetTypeByMetadataName("I1"); Assert.Equal(TypeKind.Class, a.TypeKind); Assert.NotNull(a.GetUseSiteDiagnostic()); Assert.Equal(TypeKind.Class, b.TypeKind); Assert.NotNull(b.GetUseSiteDiagnostic()); Assert.Equal(TypeKind.Class, c.TypeKind); Assert.Null(c.GetUseSiteDiagnostic()); Assert.Equal(TypeKind.Class, d.TypeKind); Assert.NotNull(d.GetUseSiteDiagnostic()); Assert.Equal(TypeKind.Interface, i1.TypeKind); Assert.Null(i1.GetUseSiteDiagnostic()); var compilation5 = CreateEmptyCompilation(source2, options: TestOptions.ReleaseDll, references: new[] { compilation1.ToMetadataReference() }); compilation5.VerifyEmitDiagnostics( // warning CS8021: No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options. Diagnostic(ErrorCode.WRN_NoRuntimeMetadataVersion).WithLocation(1, 1) ); CompileAndVerify(compilation5); Assert.Equal(TypeKind.Struct, compilation5.GetTypeByMetadataName("A").TypeKind); Assert.Equal(TypeKind.Enum, compilation5.GetTypeByMetadataName("B").TypeKind); Assert.Equal(TypeKind.Class, compilation5.GetTypeByMetadataName("C").TypeKind); Assert.Equal(TypeKind.Delegate, compilation5.GetTypeByMetadataName("D").TypeKind); Assert.Equal(TypeKind.Interface, compilation5.GetTypeByMetadataName("I1").TypeKind); var compilation6 = CreateEmptyCompilation(source2, options: TestOptions.ReleaseDll, references: new[] { compilation1.EmitToImageReference(), MscorlibRef }); compilation6.VerifyDiagnostics( // (4,10): error CS0012: The type 'ValueType' is defined in an assembly that is not referenced. You must add a reference to assembly 'mincorlib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2'. // I1 M(A a, B b, C c, D d); Diagnostic(ErrorCode.ERR_NoTypeDef, "A").WithArguments("System.ValueType", "mincorlib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2").WithLocation(4, 10), // (4,15): error CS0012: The type 'Enum' is defined in an assembly that is not referenced. You must add a reference to assembly 'mincorlib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2'. // I1 M(A a, B b, C c, D d); Diagnostic(ErrorCode.ERR_NoTypeDef, "B").WithArguments("System.Enum", "mincorlib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2").WithLocation(4, 15), // (4,25): error CS0012: The type 'MulticastDelegate' is defined in an assembly that is not referenced. You must add a reference to assembly 'mincorlib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2'. // I1 M(A a, B b, C c, D d); Diagnostic(ErrorCode.ERR_NoTypeDef, "D").WithArguments("System.MulticastDelegate", "mincorlib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2").WithLocation(4, 25) ); a = compilation6.GetTypeByMetadataName("A"); b = compilation6.GetTypeByMetadataName("B"); c = compilation6.GetTypeByMetadataName("C"); d = compilation6.GetTypeByMetadataName("D"); i1 = compilation6.GetTypeByMetadataName("I1"); Assert.Equal(TypeKind.Class, a.TypeKind); Assert.NotNull(a.GetUseSiteDiagnostic()); Assert.Equal(TypeKind.Class, b.TypeKind); Assert.NotNull(b.GetUseSiteDiagnostic()); Assert.Equal(TypeKind.Class, c.TypeKind); Assert.Null(c.GetUseSiteDiagnostic()); Assert.Equal(TypeKind.Class, d.TypeKind); Assert.NotNull(d.GetUseSiteDiagnostic()); Assert.Equal(TypeKind.Interface, i1.TypeKind); Assert.Null(i1.GetUseSiteDiagnostic()); var compilation7 = CreateEmptyCompilation(source2, options: TestOptions.ReleaseDll, references: new[] { compilation1.ToMetadataReference(), MscorlibRef }); compilation7.VerifyEmitDiagnostics(); CompileAndVerify(compilation7); Assert.Equal(TypeKind.Struct, compilation7.GetTypeByMetadataName("A").TypeKind); Assert.Equal(TypeKind.Enum, compilation7.GetTypeByMetadataName("B").TypeKind); Assert.Equal(TypeKind.Class, compilation7.GetTypeByMetadataName("C").TypeKind); Assert.Equal(TypeKind.Delegate, compilation7.GetTypeByMetadataName("D").TypeKind); Assert.Equal(TypeKind.Interface, compilation7.GetTypeByMetadataName("I1").TypeKind); } [Fact, WorkItem(15435, "https://github.com/dotnet/roslyn/issues/15435")] public void TestGettingAssemblyIdsFromDiagnostic1() { var text = @" class C : CSharpErrors.ClassMethods { public override UnavailableClass ReturnType1() { return null; } public override UnavailableClass[] ReturnType2() { return null; } }"; var compilation = CompileWithMissingReference(text); var diagnostics = compilation.GetDiagnostics(); Assert.True(diagnostics.Any(d => d.Code == (int)ErrorCode.ERR_NoTypeDef)); foreach (var diagnostic in diagnostics) { if (diagnostic.Code == (int)ErrorCode.ERR_NoTypeDef) { var actualAssemblyId = compilation.GetUnreferencedAssemblyIdentities(diagnostic).Single(); AssemblyIdentity expectedAssemblyId; AssemblyIdentity.TryParseDisplayName("Unavailable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", out expectedAssemblyId); Assert.Equal(actualAssemblyId, expectedAssemblyId); } } } private static readonly MetadataReference UnmanagedUseSiteError_Ref1 = CreateCompilation(@" public struct S1 { public int i; }", assemblyName: "libS1").ToMetadataReference(); private static readonly MetadataReference UnmanagedUseSiteError_Ref2 = CreateCompilation(@" public struct S2 { public S1 s1; } ", references: new[] { UnmanagedUseSiteError_Ref1 }, assemblyName: "libS2").ToMetadataReference(); [Fact] public void Unmanaged_UseSiteError_01() { var source = @" class C { unsafe void M(S2 s2) { var ptr = &s2; } } "; var comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll, references: new[] { UnmanagedUseSiteError_Ref2 }); comp.VerifyEmitDiagnostics( // (6,19): error CS0012: The type 'S1' is defined in an assembly that is not referenced. You must add a reference to assembly 'libS1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // var ptr = &s2; Diagnostic(ErrorCode.ERR_NoTypeDef, "&s2").WithArguments("S1", "libS1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 19), // (6,19): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('S2') // var ptr = &s2; Diagnostic(ErrorCode.ERR_ManagedAddr, "&s2").WithArguments("S2").WithLocation(6, 19) ); comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll, references: new[] { UnmanagedUseSiteError_Ref1, UnmanagedUseSiteError_Ref2 }); comp.VerifyEmitDiagnostics(); } [Fact] public void Unmanaged_UseSiteError_02() { var source = @" class C { unsafe void M() { var size = sizeof(S2); } } "; var comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll, references: new[] { UnmanagedUseSiteError_Ref2 }); comp.VerifyEmitDiagnostics( // (6,20): error CS0012: The type 'S1' is defined in an assembly that is not referenced. You must add a reference to assembly 'libS1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // var size = sizeof(S2); Diagnostic(ErrorCode.ERR_NoTypeDef, "sizeof(S2)").WithArguments("S1", "libS1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 20), // (6,20): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('S2') // var size = sizeof(S2); Diagnostic(ErrorCode.ERR_ManagedAddr, "sizeof(S2)").WithArguments("S2").WithLocation(6, 20)); comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll, references: new[] { UnmanagedUseSiteError_Ref1, UnmanagedUseSiteError_Ref2 }); comp.VerifyEmitDiagnostics(); } [Fact] public void Unmanaged_UseSiteError_03() { var source = @" class C { unsafe void M(S2* ptr) { } } "; var comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll, references: new[] { UnmanagedUseSiteError_Ref2 }); comp.VerifyEmitDiagnostics( // (4,23): error CS0012: The type 'S1' is defined in an assembly that is not referenced. You must add a reference to assembly 'libS1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // unsafe void M(S2* ptr) Diagnostic(ErrorCode.ERR_NoTypeDef, "ptr").WithArguments("S1", "libS1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(4, 23), // (4,23): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('S2') // unsafe void M(S2* ptr) Diagnostic(ErrorCode.ERR_ManagedAddr, "ptr").WithArguments("S2").WithLocation(4, 23)); comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll, references: new[] { UnmanagedUseSiteError_Ref1, UnmanagedUseSiteError_Ref2 }); comp.VerifyEmitDiagnostics(); } [Fact] public void Unmanaged_UseSiteError_04() { var source = @" class C { unsafe void M() { S2* span = stackalloc S2[16]; S2* span2 = stackalloc [] { default(S2) }; } } "; var comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll, references: new[] { UnmanagedUseSiteError_Ref2 }); comp.VerifyEmitDiagnostics( // (6,9): error CS0012: The type 'S1' is defined in an assembly that is not referenced. You must add a reference to assembly 'libS1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // S2* span = stackalloc S2[16]; Diagnostic(ErrorCode.ERR_NoTypeDef, "S2*").WithArguments("S1", "libS1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 9), // (6,9): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('S2') // S2* span = stackalloc S2[16]; Diagnostic(ErrorCode.ERR_ManagedAddr, "S2*").WithArguments("S2").WithLocation(6, 9), // (6,31): error CS0012: The type 'S1' is defined in an assembly that is not referenced. You must add a reference to assembly 'libS1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // S2* span = stackalloc S2[16]; Diagnostic(ErrorCode.ERR_NoTypeDef, "S2").WithArguments("S1", "libS1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 31), // (6,31): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('S2') // S2* span = stackalloc S2[16]; Diagnostic(ErrorCode.ERR_ManagedAddr, "S2").WithArguments("S2").WithLocation(6, 31), // (7,9): error CS0012: The type 'S1' is defined in an assembly that is not referenced. You must add a reference to assembly 'libS1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // S2* span2 = stackalloc [] { default(S2) }; Diagnostic(ErrorCode.ERR_NoTypeDef, "S2*").WithArguments("S1", "libS1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 9), // (7,9): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('S2') // S2* span2 = stackalloc [] { default(S2) }; Diagnostic(ErrorCode.ERR_ManagedAddr, "S2*").WithArguments("S2").WithLocation(7, 9), // (7,21): error CS0012: The type 'S1' is defined in an assembly that is not referenced. You must add a reference to assembly 'libS1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // S2* span2 = stackalloc [] { default(S2) }; Diagnostic(ErrorCode.ERR_NoTypeDef, "stackalloc [] { default(S2) }").WithArguments("S1", "libS1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 21), // (7,21): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('S2') // S2* span2 = stackalloc [] { default(S2) }; Diagnostic(ErrorCode.ERR_ManagedAddr, "stackalloc [] { default(S2) }").WithArguments("S2").WithLocation(7, 21)); comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll, references: new[] { UnmanagedUseSiteError_Ref1, UnmanagedUseSiteError_Ref2 }); comp.VerifyEmitDiagnostics(); } [Fact] public void Unmanaged_UseSiteError_05() { var source = @" class C { S2 s2; unsafe void M() { fixed (S2* ptr = &s2) { } } } "; var comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll, references: new[] { UnmanagedUseSiteError_Ref2 }); comp.VerifyEmitDiagnostics( // (7,16): error CS0012: The type 'S1' is defined in an assembly that is not referenced. You must add a reference to assembly 'libS1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // fixed (S2* ptr = &s2) Diagnostic(ErrorCode.ERR_NoTypeDef, "S2*").WithArguments("S1", "libS1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 16), // (7,16): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('S2') // fixed (S2* ptr = &s2) Diagnostic(ErrorCode.ERR_ManagedAddr, "S2*").WithArguments("S2").WithLocation(7, 16), // (7,26): error CS0012: The type 'S1' is defined in an assembly that is not referenced. You must add a reference to assembly 'libS1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // fixed (S2* ptr = &s2) Diagnostic(ErrorCode.ERR_NoTypeDef, "&s2").WithArguments("S1", "libS1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 26), // (7,26): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('S2') // fixed (S2* ptr = &s2) Diagnostic(ErrorCode.ERR_ManagedAddr, "&s2").WithArguments("S2").WithLocation(7, 26) ); comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll, references: new[] { UnmanagedUseSiteError_Ref1, UnmanagedUseSiteError_Ref2 }); comp.VerifyEmitDiagnostics(); } [Fact] public void Unmanaged_UseSiteError_06() { var source = @" class C { void M<T>(T t) where T : unmanaged { } void M1() { M(default(S2)); // 1, 2 M(default(S2)); // 3, 4 } } "; var comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll, references: new[] { UnmanagedUseSiteError_Ref2 }); comp.VerifyEmitDiagnostics( // (8,9): error CS8377: The type 'S2' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'C.M<T>(T)' // M(default(S2)); // 1, 2 Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M").WithArguments("C.M<T>(T)", "T", "S2").WithLocation(8, 9), // (8,9): error CS0012: The type 'S1' is defined in an assembly that is not referenced. You must add a reference to assembly 'libS1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // M(default(S2)); // 1, 2 Diagnostic(ErrorCode.ERR_NoTypeDef, "M").WithArguments("S1", "libS1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(8, 9), // (9,9): error CS8377: The type 'S2' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'C.M<T>(T)' // M(default(S2)); // 3, 4 Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M").WithArguments("C.M<T>(T)", "T", "S2").WithLocation(9, 9), // (9,9): error CS0012: The type 'S1' is defined in an assembly that is not referenced. You must add a reference to assembly 'libS1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // M(default(S2)); // 3, 4 Diagnostic(ErrorCode.ERR_NoTypeDef, "M").WithArguments("S1", "libS1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(9, 9)); comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll, references: new[] { UnmanagedUseSiteError_Ref1, UnmanagedUseSiteError_Ref2 }); comp.VerifyEmitDiagnostics(); } [Fact] public void Unmanaged_UseSiteError_07() { var source = @" public struct S3 { public S2 s2; } class C { void M<T>(T t) where T : unmanaged { } void M1() { M(default(S3)); // 1, 2 M(default(S3)); // 3, 4 } } "; var comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll, references: new[] { UnmanagedUseSiteError_Ref2 }); comp.VerifyEmitDiagnostics( // (13,9): error CS8377: The type 'S3' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'C.M<T>(T)' // M(default(S3)); // 1, 2 Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M").WithArguments("C.M<T>(T)", "T", "S3").WithLocation(13, 9), // (13,9): error CS0012: The type 'S1' is defined in an assembly that is not referenced. You must add a reference to assembly 'libS1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // M(default(S3)); // 1, 2 Diagnostic(ErrorCode.ERR_NoTypeDef, "M").WithArguments("S1", "libS1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(13, 9), // (14,9): error CS8377: The type 'S3' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'C.M<T>(T)' // M(default(S3)); // 3, 4 Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M").WithArguments("C.M<T>(T)", "T", "S3").WithLocation(14, 9), // (14,9): error CS0012: The type 'S1' is defined in an assembly that is not referenced. You must add a reference to assembly 'libS1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // M(default(S3)); // 3, 4 Diagnostic(ErrorCode.ERR_NoTypeDef, "M").WithArguments("S1", "libS1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(14, 9)); comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll, references: new[] { UnmanagedUseSiteError_Ref1, UnmanagedUseSiteError_Ref2 }); comp.VerifyEmitDiagnostics(); } [Fact] public void Unmanaged_UseSiteError_08() { var source = @" using System.Threading.Tasks; using System; class C { async Task M1() { S2 s2 = M2(); await M1(); Console.Write(s2); } S2 M2() => default; } "; var comp = CreateCompilation(source, references: new[] { UnmanagedUseSiteError_Ref2 }); comp.VerifyEmitDiagnostics( // error CS0012: The type 'S1' is defined in an assembly that is not referenced. You must add a reference to assembly 'libS1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Diagnostic(ErrorCode.ERR_NoTypeDef).WithArguments("S1", "libS1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(1, 1), // error CS0012: The type 'S1' is defined in an assembly that is not referenced. You must add a reference to assembly 'libS1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Diagnostic(ErrorCode.ERR_NoTypeDef).WithArguments("S1", "libS1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(1, 1)); comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll, references: new[] { UnmanagedUseSiteError_Ref1, UnmanagedUseSiteError_Ref2 }); comp.VerifyEmitDiagnostics(); } [Fact] public void Unmanaged_UseSiteError_09() { var source = @" public struct S3 { public S2 s2; } "; var comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll, references: new[] { UnmanagedUseSiteError_Ref2 }); comp.VerifyEmitDiagnostics(); var s3 = comp.GetMember<NamedTypeSymbol>("S3"); verifyIsManagedType(); verifyIsManagedType(); void verifyIsManagedType() { var managedKindUseSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(s3.ContainingAssembly); Assert.True(s3.IsManagedType(ref managedKindUseSiteInfo)); managedKindUseSiteInfo.Diagnostics.Verify( // error CS0012: The type 'S1' is defined in an assembly that is not referenced. You must add a reference to assembly 'libS1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Diagnostic(ErrorCode.ERR_NoTypeDef).WithArguments("S1", "libS1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(1, 1) ); } comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll, references: new[] { UnmanagedUseSiteError_Ref1, UnmanagedUseSiteError_Ref2 }); comp.VerifyEmitDiagnostics(); s3 = comp.GetMember<NamedTypeSymbol>("S3"); verifyIsUnmanagedType(); verifyIsUnmanagedType(); void verifyIsUnmanagedType() { var managedKindUseSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(s3.ContainingAssembly); Assert.False(s3.IsManagedType(ref managedKindUseSiteInfo)); Assert.Null(managedKindUseSiteInfo.Diagnostics); } } [Fact] public void OverrideWithModreq_01() { var il = @" .class public auto ansi beforefieldinit CL1 extends[mscorlib] System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call instance void[mscorlib] System.Object::.ctor() IL_0006: ret } .method public hidebysig newslot virtual instance int32 modreq([mscorlib]System.Runtime.CompilerServices.IsConst) get_P() cil managed { .maxstack 8 ldc.i4.s 123 ret } } // end of class CL1 "; var source = @" class Test : CL1 { public override int get_P() { return default; } } "; CreateCompilationWithIL(source, il).VerifyDiagnostics( // (4,25): error CS0570: 'CL1.get_P()' is not supported by the language // public override int get_P() Diagnostic(ErrorCode.ERR_BindToBogus, "get_P").WithArguments("CL1.get_P()").WithLocation(4, 25) ); } [Fact] public void OverrideWithModreq_02() { var il = @" .class public auto ansi beforefieldinit CL1 extends[mscorlib] System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call instance void[mscorlib] System.Object::.ctor() IL_0006: ret } .method public hidebysig newslot virtual instance int32 modreq([mscorlib]System.Runtime.CompilerServices.IsConst) get_P() cil managed { .maxstack 8 ldc.i4.s 123 ret } .property instance int32 modreq([mscorlib]System.Runtime.CompilerServices.IsConst) P() { .get instance int32 modreq([mscorlib]System.Runtime.CompilerServices.IsConst) CL1::get_P() } } // end of class CL1 "; var source = @" class Test : CL1 { public override int P { get => throw null; } } "; CreateCompilationWithIL(source, il).VerifyDiagnostics( // (4,25): error CS0569: 'Test.P': cannot override 'CL1.P' because it is not supported by the language // public override int P Diagnostic(ErrorCode.ERR_CantOverrideBogusMethod, "P").WithArguments("Test.P", "CL1.P").WithLocation(4, 25) ); } [Fact] public void OverrideWithModreq_03() { var il = @" .class public auto ansi beforefieldinit CL1 extends[mscorlib] System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call instance void[mscorlib] System.Object::.ctor() IL_0006: ret } .method public hidebysig newslot virtual instance int32 modreq([mscorlib]System.Runtime.CompilerServices.IsConst) get_P() cil managed { .maxstack 8 ldc.i4.s 123 ret } .property instance int32 P() { .get instance int32 modreq([mscorlib]System.Runtime.CompilerServices.IsConst) CL1::get_P() } } // end of class CL1 "; var source = @" class Test : CL1 { public override int P { get => throw null; } } "; CreateCompilationWithIL(source, il).VerifyDiagnostics( // (6,9): error CS0570: 'CL1.P.get' is not supported by the language // get => throw null; Diagnostic(ErrorCode.ERR_BindToBogus, "get").WithArguments("CL1.P.get").WithLocation(6, 9) ); } [Fact] public void OverrideWithModreq_04() { var il = @" .class public auto ansi beforefieldinit CL1 extends[mscorlib] System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call instance void[mscorlib] System.Object::.ctor() IL_0006: ret } .method public hidebysig newslot virtual instance void modreq([mscorlib]System.Runtime.CompilerServices.IsConst) set_P(int32 x) cil managed { .maxstack 8 ret } .property instance int32 P() { .set instance void modreq([mscorlib]System.Runtime.CompilerServices.IsConst) CL1::set_P(int32) } } // end of class CL1 "; var source = @" class Test : CL1 { public override int P { set => throw null; } } "; CreateCompilationWithIL(source, il).VerifyDiagnostics( // (6,9): error CS0570: 'CL1.P.set' is not supported by the language // set => throw null; Diagnostic(ErrorCode.ERR_BindToBogus, "set").WithArguments("CL1.P.set").WithLocation(6, 9) ); } [Fact] public void OverrideWithModreq_05() { var il = @" .class public auto ansi beforefieldinit CL1 extends[mscorlib] System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call instance void[mscorlib] System.Object::.ctor() IL_0006: ret } .method public hidebysig newslot virtual instance int32 modreq([mscorlib]System.Runtime.CompilerServices.IsConst) get_P() cil managed { .maxstack 8 ldc.i4.s 123 ret } .method public hidebysig newslot virtual instance void modreq([mscorlib]System.Runtime.CompilerServices.IsConst) set_P(int32 x) cil managed { .maxstack 8 ret } .property instance int32 P() { .get instance int32 modreq([mscorlib]System.Runtime.CompilerServices.IsConst) CL1::get_P() .set instance void modreq([mscorlib]System.Runtime.CompilerServices.IsConst) CL1::set_P(int32) } } // end of class CL1 "; var source = @" class Test : CL1 { public override int P { get => throw null; set => throw null; } } "; CreateCompilationWithIL(source, il).VerifyDiagnostics( // (6,9): error CS0570: 'CL1.P.get' is not supported by the language // get => throw null; Diagnostic(ErrorCode.ERR_BindToBogus, "get").WithArguments("CL1.P.get").WithLocation(6, 9), // (7,9): error CS0570: 'CL1.P.set' is not supported by the language // set => throw null; Diagnostic(ErrorCode.ERR_BindToBogus, "set").WithArguments("CL1.P.set").WithLocation(7, 9) ); } [Fact] public void OverrideWithModreq_06() { var il = @" .class public auto ansi beforefieldinit CL1 extends[mscorlib] System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call instance void[mscorlib] System.Object::.ctor() IL_0006: ret } .method public hidebysig newslot virtual instance int32 get_P() cil managed { .maxstack 8 ldc.i4.s 123 ret } .method public hidebysig newslot virtual instance void modreq([mscorlib]System.Runtime.CompilerServices.IsConst) set_P(int32 x) cil managed { .maxstack 8 ret } .property instance int32 P() { .get instance int32 CL1::get_P() .set instance void modreq([mscorlib]System.Runtime.CompilerServices.IsConst) CL1::set_P(int32) } } // end of class CL1 "; var source = @" class Test : CL1 { public override int P { get => throw null; set => throw null; } } "; CreateCompilationWithIL(source, il).VerifyDiagnostics( // (7,9): error CS0570: 'CL1.P.set' is not supported by the language // set => throw null; Diagnostic(ErrorCode.ERR_BindToBogus, "set").WithArguments("CL1.P.set").WithLocation(7, 9) ); } [Fact] public void OverrideWithModreq_07() { var il = @" .class public auto ansi beforefieldinit CL1 extends[mscorlib] System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call instance void[mscorlib] System.Object::.ctor() IL_0006: ret } .method public hidebysig newslot virtual instance int32 modreq([mscorlib]System.Runtime.CompilerServices.IsConst) get_P() cil managed { .maxstack 8 ldc.i4.s 123 ret } .method public hidebysig newslot virtual instance void set_P(int32 x) cil managed { .maxstack 8 ret } .property instance int32 P() { .get instance int32 modreq([mscorlib]System.Runtime.CompilerServices.IsConst) CL1::get_P() .set instance void CL1::set_P(int32) } } // end of class CL1 "; var source = @" class Test : CL1 { public override int P { get => throw null; set => throw null; } } "; CreateCompilationWithIL(source, il).VerifyDiagnostics( // (6,9): error CS0570: 'CL1.P.get' is not supported by the language // get => throw null; Diagnostic(ErrorCode.ERR_BindToBogus, "get").WithArguments("CL1.P.get").WithLocation(6, 9) ); } [Fact] public void OverrideWithModreq_08() { var il = @" .class public auto ansi beforefieldinit CL1 extends[mscorlib] System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call instance void[mscorlib] System.Object::.ctor() IL_0006: ret } .method public hidebysig specialname newslot virtual instance void add_E ( class [mscorlib]System.Action modreq([mscorlib]System.Runtime.CompilerServices.IsConst) 'value' ) cil managed { ret } .method public hidebysig specialname newslot virtual instance void remove_E ( class [mscorlib]System.Action modreq([mscorlib]System.Runtime.CompilerServices.IsConst) 'value' ) cil managed { ret } .event [mscorlib]System.Action E { .addon instance void CL1::add_E(class [mscorlib]System.Action modreq([mscorlib]System.Runtime.CompilerServices.IsConst)) .removeon instance void CL1::remove_E(class [mscorlib]System.Action modreq([mscorlib]System.Runtime.CompilerServices.IsConst)) } } // end of class CL1 "; var source = @" class Test : CL1 { public override event System.Action E { add => throw null; remove => throw null; } } "; CreateCompilationWithIL(source, il).VerifyDiagnostics( // (6,9): error CS0570: 'CL1.E.add' is not supported by the language // add => throw null; Diagnostic(ErrorCode.ERR_BindToBogus, "add").WithArguments("CL1.E.add").WithLocation(6, 9), // (7,9): error CS0570: 'CL1.E.remove' is not supported by the language // remove => throw null; Diagnostic(ErrorCode.ERR_BindToBogus, "remove").WithArguments("CL1.E.remove").WithLocation(7, 9) ); } [Fact] public void OverrideWithModreq_09() { var il = @" .class public auto ansi beforefieldinit CL1 extends[mscorlib] System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call instance void[mscorlib] System.Object::.ctor() IL_0006: ret } .method public hidebysig specialname newslot virtual instance void add_E ( class [mscorlib]System.Action 'value' ) cil managed { ret } .method public hidebysig specialname newslot virtual instance void remove_E ( class [mscorlib]System.Action modreq([mscorlib]System.Runtime.CompilerServices.IsConst) 'value' ) cil managed { ret } .event [mscorlib]System.Action E { .addon instance void CL1::add_E(class [mscorlib]System.Action) .removeon instance void CL1::remove_E(class [mscorlib]System.Action modreq([mscorlib]System.Runtime.CompilerServices.IsConst)) } } // end of class CL1 "; var source = @" class Test : CL1 { public override event System.Action E { add => throw null; remove => throw null; } } "; CreateCompilationWithIL(source, il).VerifyDiagnostics( // (7,9): error CS0570: 'CL1.E.remove' is not supported by the language // remove => throw null; Diagnostic(ErrorCode.ERR_BindToBogus, "remove").WithArguments("CL1.E.remove").WithLocation(7, 9) ); } [Fact] public void OverrideWithModreq_10() { var il = @" .class public auto ansi beforefieldinit CL1 extends[mscorlib] System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call instance void[mscorlib] System.Object::.ctor() IL_0006: ret } .method public hidebysig specialname newslot virtual instance void add_E ( class [mscorlib]System.Action modreq([mscorlib]System.Runtime.CompilerServices.IsConst) 'value' ) cil managed { ret } .method public hidebysig specialname newslot virtual instance void remove_E ( class [mscorlib]System.Action 'value' ) cil managed { ret } .event [mscorlib]System.Action E { .addon instance void CL1::add_E(class [mscorlib]System.Action modreq([mscorlib]System.Runtime.CompilerServices.IsConst)) .removeon instance void CL1::remove_E(class [mscorlib]System.Action) } } // end of class CL1 "; var source = @" class Test : CL1 { public override event System.Action E { add => throw null; remove => throw null; } } "; CreateCompilationWithIL(source, il).VerifyDiagnostics( // (6,9): error CS0570: 'CL1.E.add' is not supported by the language // add => throw null; Diagnostic(ErrorCode.ERR_BindToBogus, "add").WithArguments("CL1.E.add").WithLocation(6, 9) ); } [Fact] public void ImplementWithModreq_01() { var il = @" .class interface public abstract auto ansi CL1 { .method public hidebysig newslot specialname abstract virtual instance int32 modreq([mscorlib]System.Runtime.CompilerServices.IsConst) get_P() cil managed { } } // end of class CL1 "; var source = @" class Test : CL1 { public int get_P() { return default; } } "; CreateCompilationWithIL(source, il).VerifyDiagnostics( // (4,16): error CS0570: 'CL1.get_P()' is not supported by the language // public int get_P() Diagnostic(ErrorCode.ERR_BindToBogus, "get_P").WithArguments("CL1.get_P()").WithLocation(4, 16) ); } [Fact] public void ImplementWithModreq_02() { var il = @" .class interface public abstract auto ansi CL1 { .method public hidebysig newslot specialname abstract virtual instance int32 modreq([mscorlib]System.Runtime.CompilerServices.IsConst) get_P() cil managed { } .property instance int32 modreq([mscorlib]System.Runtime.CompilerServices.IsConst) P() { .get instance int32 modreq([mscorlib]System.Runtime.CompilerServices.IsConst) CL1::get_P() } } // end of class CL1 "; var source = @" class Test1 : CL1 { public int P { get => throw null; } } class Test2 : CL1 { int CL1.P { get => throw null; } } "; CreateCompilationWithIL(source, il).VerifyDiagnostics( // (6,9): error CS0686: Accessor 'Test1.P.get' cannot implement interface member 'CL1.get_P()' for type 'Test1'. Use an explicit interface implementation. // get => throw null; Diagnostic(ErrorCode.ERR_AccessorImplementingMethod, "get").WithArguments("Test1.P.get", "CL1.get_P()", "Test1").WithLocation(6, 9), // (12,13): error CS0682: 'Test2.CL1.P' cannot implement 'CL1.P' because it is not supported by the language // int CL1.P Diagnostic(ErrorCode.ERR_BogusExplicitImpl, "P").WithArguments("Test2.CL1.P", "CL1.P").WithLocation(12, 13), // (14,9): error CS0570: 'CL1.get_P()' is not supported by the language // get => throw null; Diagnostic(ErrorCode.ERR_BindToBogus, "get").WithArguments("CL1.get_P()").WithLocation(14, 9) ); } [Fact] public void ImplementWithModreq_03() { var il = @" .class interface public abstract auto ansi CL1 { .method public hidebysig newslot specialname abstract virtual instance int32 modreq([mscorlib]System.Runtime.CompilerServices.IsConst) get_P() cil managed { } .property instance int32 P() { .get instance int32 modreq([mscorlib]System.Runtime.CompilerServices.IsConst) CL1::get_P() } } // end of class CL1 "; var source = @" class Test1 : CL1 { public int P { get => throw null; } } class Test2 : CL1 { int CL1.P { get => throw null; } } "; CreateCompilationWithIL(source, il).VerifyDiagnostics( // (6,9): error CS0570: 'CL1.P.get' is not supported by the language // get => throw null; Diagnostic(ErrorCode.ERR_BindToBogus, "get").WithArguments("CL1.P.get").WithLocation(6, 9), // (14,9): error CS0570: 'CL1.P.get' is not supported by the language // get => throw null; Diagnostic(ErrorCode.ERR_BindToBogus, "get").WithArguments("CL1.P.get").WithLocation(14, 9) ); } [Fact] public void ImplementWithModreq_04() { var il = @" .class interface public abstract auto ansi CL1 { .method public hidebysig newslot specialname abstract virtual instance void modreq([mscorlib]System.Runtime.CompilerServices.IsConst) set_P(int32 x) cil managed { } .property instance int32 P() { .set instance void modreq([mscorlib]System.Runtime.CompilerServices.IsConst) CL1::set_P(int32) } } // end of class CL1 "; var source = @" class Test1 : CL1 { public int P { set => throw null; } } class Test2 : CL1 { int CL1.P { set => throw null; } } "; CreateCompilationWithIL(source, il).VerifyDiagnostics( // (6,9): error CS0570: 'CL1.P.set' is not supported by the language // set => throw null; Diagnostic(ErrorCode.ERR_BindToBogus, "set").WithArguments("CL1.P.set").WithLocation(6, 9), // (14,9): error CS0570: 'CL1.P.set' is not supported by the language // set => throw null; Diagnostic(ErrorCode.ERR_BindToBogus, "set").WithArguments("CL1.P.set").WithLocation(14, 9) ); } [Fact] public void ImplementWithModreq_05() { var il = @" .class interface public abstract auto ansi CL1 { .method public hidebysig newslot specialname abstract virtual instance int32 modreq([mscorlib]System.Runtime.CompilerServices.IsConst) get_P() cil managed { } .method public hidebysig newslot specialname abstract virtual instance void modreq([mscorlib]System.Runtime.CompilerServices.IsConst) set_P(int32 x) cil managed { } .property instance int32 P() { .get instance int32 modreq([mscorlib]System.Runtime.CompilerServices.IsConst) CL1::get_P() .set instance void modreq([mscorlib]System.Runtime.CompilerServices.IsConst) CL1::set_P(int32) } } // end of class CL1 "; var source = @" class Test1 : CL1 { public int P { get => throw null; set => throw null; } } class Test2 : CL1 { int CL1.P { get => throw null; set => throw null; } } "; CreateCompilationWithIL(source, il).VerifyDiagnostics( // (6,9): error CS0570: 'CL1.P.get' is not supported by the language // get => throw null; Diagnostic(ErrorCode.ERR_BindToBogus, "get").WithArguments("CL1.P.get").WithLocation(6, 9), // (7,9): error CS0570: 'CL1.P.set' is not supported by the language // set => throw null; Diagnostic(ErrorCode.ERR_BindToBogus, "set").WithArguments("CL1.P.set").WithLocation(7, 9), // (15,9): error CS0570: 'CL1.P.get' is not supported by the language // get => throw null; Diagnostic(ErrorCode.ERR_BindToBogus, "get").WithArguments("CL1.P.get").WithLocation(15, 9), // (16,9): error CS0570: 'CL1.P.set' is not supported by the language // set => throw null; Diagnostic(ErrorCode.ERR_BindToBogus, "set").WithArguments("CL1.P.set").WithLocation(16, 9) ); } [Fact] public void ImplementWithModreq_06() { var il = @" .class interface public abstract auto ansi CL1 { .method public hidebysig newslot specialname abstract virtual instance int32 get_P() cil managed { } .method public hidebysig newslot specialname abstract virtual instance void modreq([mscorlib]System.Runtime.CompilerServices.IsConst) set_P(int32 x) cil managed { } .property instance int32 P() { .get instance int32 CL1::get_P() .set instance void modreq([mscorlib]System.Runtime.CompilerServices.IsConst) CL1::set_P(int32) } } // end of class CL1 "; var source = @" class Test1 : CL1 { public int P { get => throw null; set => throw null; } } class Test2 : CL1 { int CL1.P { get => throw null; set => throw null; } } "; CreateCompilationWithIL(source, il).VerifyDiagnostics( // (7,9): error CS0570: 'CL1.P.set' is not supported by the language // set => throw null; Diagnostic(ErrorCode.ERR_BindToBogus, "set").WithArguments("CL1.P.set").WithLocation(7, 9), // (16,9): error CS0570: 'CL1.P.set' is not supported by the language // set => throw null; Diagnostic(ErrorCode.ERR_BindToBogus, "set").WithArguments("CL1.P.set").WithLocation(16, 9) ); } [Fact] public void ImplementWithModreq_07() { var il = @" .class interface public abstract auto ansi CL1 { .method public hidebysig newslot specialname abstract virtual instance int32 modreq([mscorlib]System.Runtime.CompilerServices.IsConst) get_P() cil managed { } .method public hidebysig newslot specialname abstract virtual instance void set_P(int32 x) cil managed { } .property instance int32 P() { .get instance int32 modreq([mscorlib]System.Runtime.CompilerServices.IsConst) CL1::get_P() .set instance void CL1::set_P(int32) } } // end of class CL1 "; var source = @" class Test1 : CL1 { public int P { get => throw null; set => throw null; } } class Test2 : CL1 { int CL1.P { get => throw null; set => throw null; } } "; CreateCompilationWithIL(source, il).VerifyDiagnostics( // (6,9): error CS0570: 'CL1.P.get' is not supported by the language // get => throw null; Diagnostic(ErrorCode.ERR_BindToBogus, "get").WithArguments("CL1.P.get").WithLocation(6, 9), // (15,9): error CS0570: 'CL1.P.get' is not supported by the language // get => throw null; Diagnostic(ErrorCode.ERR_BindToBogus, "get").WithArguments("CL1.P.get").WithLocation(15, 9) ); } [Fact] public void ImplementWithModreq_08() { var il = @" .class interface public abstract auto ansi CL1 { .method public hidebysig specialname newslot abstract virtual instance void add_E ( class [mscorlib]System.Action modreq([mscorlib]System.Runtime.CompilerServices.IsConst) 'value' ) cil managed { } .method public hidebysig specialname newslot abstract virtual instance void remove_E ( class [mscorlib]System.Action modreq([mscorlib]System.Runtime.CompilerServices.IsConst) 'value' ) cil managed { } .event [mscorlib]System.Action E { .addon instance void CL1::add_E(class [mscorlib]System.Action modreq([mscorlib]System.Runtime.CompilerServices.IsConst)) .removeon instance void CL1::remove_E(class [mscorlib]System.Action modreq([mscorlib]System.Runtime.CompilerServices.IsConst)) } } // end of class CL1 "; var source = @" class Test1 : CL1 { public event System.Action E { add => throw null; remove => throw null; } } class Test2 : CL1 { event System.Action CL1.E { add => throw null; remove => throw null; } } "; CreateCompilationWithIL(source, il).VerifyDiagnostics( // (6,9): error CS0570: 'CL1.E.add' is not supported by the language // add => throw null; Diagnostic(ErrorCode.ERR_BindToBogus, "add").WithArguments("CL1.E.add").WithLocation(6, 9), // (7,9): error CS0570: 'CL1.E.remove' is not supported by the language // remove => throw null; Diagnostic(ErrorCode.ERR_BindToBogus, "remove").WithArguments("CL1.E.remove").WithLocation(7, 9), // (15,9): error CS0570: 'CL1.E.add' is not supported by the language // add => throw null; Diagnostic(ErrorCode.ERR_BindToBogus, "add").WithArguments("CL1.E.add").WithLocation(15, 9), // (16,9): error CS0570: 'CL1.E.remove' is not supported by the language // remove => throw null; Diagnostic(ErrorCode.ERR_BindToBogus, "remove").WithArguments("CL1.E.remove").WithLocation(16, 9) ); } [Fact] public void ImplementWithModreq_09() { var il = @" .class interface public abstract auto ansi CL1 { .method public hidebysig specialname newslot abstract virtual instance void add_E ( class [mscorlib]System.Action 'value' ) cil managed { } .method public hidebysig specialname newslot abstract virtual instance void remove_E ( class [mscorlib]System.Action modreq([mscorlib]System.Runtime.CompilerServices.IsConst) 'value' ) cil managed { } .event [mscorlib]System.Action E { .addon instance void CL1::add_E(class [mscorlib]System.Action) .removeon instance void CL1::remove_E(class [mscorlib]System.Action modreq([mscorlib]System.Runtime.CompilerServices.IsConst)) } } // end of class CL1 "; var source = @" class Test1 : CL1 { public event System.Action E { add => throw null; remove => throw null; } } class Test2 : CL1 { event System.Action CL1.E { add => throw null; remove => throw null; } } "; CreateCompilationWithIL(source, il).VerifyDiagnostics( // (7,9): error CS0570: 'CL1.E.remove' is not supported by the language // remove => throw null; Diagnostic(ErrorCode.ERR_BindToBogus, "remove").WithArguments("CL1.E.remove").WithLocation(7, 9), // (16,9): error CS0570: 'CL1.E.remove' is not supported by the language // remove => throw null; Diagnostic(ErrorCode.ERR_BindToBogus, "remove").WithArguments("CL1.E.remove").WithLocation(16, 9) ); } [Fact] public void ImplementWithModreq_10() { var il = @" .class interface public abstract auto ansi CL1 { .method public hidebysig specialname newslot abstract virtual instance void add_E ( class [mscorlib]System.Action modreq([mscorlib]System.Runtime.CompilerServices.IsConst) 'value' ) cil managed { } .method public hidebysig specialname newslot abstract virtual instance void remove_E ( class [mscorlib]System.Action 'value' ) cil managed { } .event [mscorlib]System.Action E { .addon instance void CL1::add_E(class [mscorlib]System.Action modreq([mscorlib]System.Runtime.CompilerServices.IsConst)) .removeon instance void CL1::remove_E(class [mscorlib]System.Action) } } // end of class CL1 "; var source = @" class Test1 : CL1 { public event System.Action E { add => throw null; remove => throw null; } } class Test2 : CL1 { event System.Action CL1.E { add => throw null; remove => throw null; } } "; CreateCompilationWithIL(source, il).VerifyDiagnostics( // (6,9): error CS0570: 'CL1.E.add' is not supported by the language // add => throw null; Diagnostic(ErrorCode.ERR_BindToBogus, "add").WithArguments("CL1.E.add").WithLocation(6, 9), // (15,9): error CS0570: 'CL1.E.add' is not supported by the language // add => throw null; Diagnostic(ErrorCode.ERR_BindToBogus, "add").WithArguments("CL1.E.add").WithLocation(15, 9) ); } } }
-1
dotnet/roslyn
56,310
Move semantic classification caching down to Editor layer
CyrusNajmabadi
"2021-09-09T23:15:16Z"
"2021-09-10T19:26:25Z"
6e123012d868c56aba8acabfe1ccad1bf8f20b04
7af13b6e3867198cd59c566a905b332888ea1dec
Move semantic classification caching down to Editor layer.
./src/Workspaces/CSharp/Portable/ExternalAccess/Pythia/Api/PythiaSyntaxExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.CSharp.Syntax; namespace Microsoft.CodeAnalysis.ExternalAccess.Pythia.Api { internal static partial class PythiaSyntaxExtensions { public static bool IsInNonUserCode(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) => CSharp.Extensions.SyntaxTreeExtensions.IsInNonUserCode(syntaxTree, position, cancellationToken); public static SyntaxToken GetPreviousTokenIfTouchingWord(this SyntaxToken token, int position) => CSharp.Extensions.SyntaxTokenExtensions.GetPreviousTokenIfTouchingWord(token, position); public static SyntaxToken FindTokenOnLeftOfPosition(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken, bool includeSkipped = true, bool includeDirectives = false, bool includeDocumentationComments = false) => Shared.Extensions.SyntaxTreeExtensions.FindTokenOnLeftOfPosition(syntaxTree, position, cancellationToken, includeSkipped, includeDirectives, includeDocumentationComments); public static bool IsFoundUnder<TParent>(this SyntaxNode node, Func<TParent, SyntaxNode> childGetter) where TParent : SyntaxNode => Shared.Extensions.SyntaxNodeExtensions.IsFoundUnder(node, childGetter); public static SimpleNameSyntax? GetRightmostName(this ExpressionSyntax node) => CSharp.Extensions.ExpressionSyntaxExtensions.GetRightmostName(node); public static bool IsInStaticContext(this SyntaxNode node) => CSharp.Extensions.SyntaxNodeExtensions.IsInStaticContext(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. using System; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.ExternalAccess.Pythia.Api { internal static partial class PythiaSyntaxExtensions { public static bool IsInNonUserCode(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) => CSharp.Extensions.SyntaxTreeExtensions.IsInNonUserCode(syntaxTree, position, cancellationToken); public static SyntaxToken GetPreviousTokenIfTouchingWord(this SyntaxToken token, int position) => CSharp.Extensions.SyntaxTokenExtensions.GetPreviousTokenIfTouchingWord(token, position); public static SyntaxToken FindTokenOnLeftOfPosition(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken, bool includeSkipped = true, bool includeDirectives = false, bool includeDocumentationComments = false) => Shared.Extensions.SyntaxTreeExtensions.FindTokenOnLeftOfPosition(syntaxTree, position, cancellationToken, includeSkipped, includeDirectives, includeDocumentationComments); public static bool IsFoundUnder<TParent>(this SyntaxNode node, Func<TParent, SyntaxNode> childGetter) where TParent : SyntaxNode => Shared.Extensions.SyntaxNodeExtensions.IsFoundUnder(node, childGetter); public static SimpleNameSyntax? GetRightmostName(this ExpressionSyntax node) => CSharp.Extensions.ExpressionSyntaxExtensions.GetRightmostName(node); public static bool IsInStaticContext(this SyntaxNode node) => CSharp.Extensions.SyntaxNodeExtensions.IsInStaticContext(node); } }
-1
dotnet/roslyn
56,310
Move semantic classification caching down to Editor layer
CyrusNajmabadi
"2021-09-09T23:15:16Z"
"2021-09-10T19:26:25Z"
6e123012d868c56aba8acabfe1ccad1bf8f20b04
7af13b6e3867198cd59c566a905b332888ea1dec
Move semantic classification caching down to Editor layer.
./src/VisualStudio/IntegrationTest/TestUtilities/OutOfProcess/VisualStudioWorkspace_OutOfProc.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.VisualStudio.IntegrationTest.Utilities.InProcess; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.OutOfProcess { public class VisualStudioWorkspace_OutOfProc : OutOfProcComponent { private readonly VisualStudioWorkspace_InProc _inProc; internal VisualStudioWorkspace_OutOfProc(VisualStudioInstance visualStudioInstance) : base(visualStudioInstance) { _inProc = CreateInProcComponent<VisualStudioWorkspace_InProc>(visualStudioInstance); } public void SetOptionInfer(string projectName, bool value) { _inProc.SetOptionInfer(projectName, value); WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace); } public void SetPersistenceOption(bool value) => SetOption("Enabled", PersistentStorageOptions.OptionName, value); public bool IsPrettyListingOn(string languageName) => _inProc.IsPrettyListingOn(languageName); public void SetPrettyListing(string languageName, bool value) => _inProc.SetPrettyListing(languageName, value); public void SetPerLanguageOption(string optionName, string feature, string language, object value) => _inProc.SetPerLanguageOption(optionName, feature, language, value); public void SetOption(string optionName, string feature, object value) => _inProc.SetOption(optionName, feature, value); public void WaitForAsyncOperations(TimeSpan timeout, string featuresToWaitFor, bool waitForWorkspaceFirst = true) => _inProc.WaitForAsyncOperations(timeout, featuresToWaitFor, waitForWorkspaceFirst); public void WaitForAllAsyncOperations(TimeSpan timeout, params string[] featureNames) => _inProc.WaitForAllAsyncOperations(timeout, featureNames); public void WaitForAllAsyncOperationsOrFail(TimeSpan timeout, params string[] featureNames) => _inProc.WaitForAllAsyncOperationsOrFail(timeout, featureNames); public void CleanUpWorkspace() => _inProc.CleanUpWorkspace(); public void ResetOptions() => _inProc.ResetOptions(); public void CleanUpWaitingService() => _inProc.CleanUpWaitingService(); public void SetQuickInfo(bool value) => _inProc.EnableQuickInfo(value); public void SetImportCompletionOption(bool value) { SetPerLanguageOption( optionName: "ShowItemsFromUnimportedNamespaces", feature: "CompletionOptions", language: LanguageNames.CSharp, value: value); SetPerLanguageOption( optionName: "ShowItemsFromUnimportedNamespaces", feature: "CompletionOptions", language: LanguageNames.VisualBasic, value: value); } public void SetArgumentCompletionSnippetsOption(bool value) { SetPerLanguageOption( optionName: CompletionOptions.EnableArgumentCompletionSnippets.Name, feature: CompletionOptions.EnableArgumentCompletionSnippets.Feature, language: LanguageNames.CSharp, value: value); SetPerLanguageOption( optionName: CompletionOptions.EnableArgumentCompletionSnippets.Name, feature: CompletionOptions.EnableArgumentCompletionSnippets.Feature, language: LanguageNames.VisualBasic, value: value); } public void SetTriggerCompletionInArgumentLists(bool value) { SetPerLanguageOption( optionName: CompletionOptions.TriggerInArgumentLists.Name, feature: CompletionOptions.TriggerInArgumentLists.Feature, language: LanguageNames.CSharp, value: value); } public void SetFullSolutionAnalysis(bool value) { SetPerLanguageOption( optionName: SolutionCrawlerOptions.BackgroundAnalysisScopeOption.Name, feature: SolutionCrawlerOptions.BackgroundAnalysisScopeOption.Feature, language: LanguageNames.CSharp, value: value ? BackgroundAnalysisScope.FullSolution : BackgroundAnalysisScope.Default); SetPerLanguageOption( optionName: SolutionCrawlerOptions.BackgroundAnalysisScopeOption.Name, feature: SolutionCrawlerOptions.BackgroundAnalysisScopeOption.Feature, language: LanguageNames.VisualBasic, value: value ? BackgroundAnalysisScope.FullSolution : BackgroundAnalysisScope.Default); } public void SetEnableOpeningSourceGeneratedFilesInWorkspaceExperiment(bool value) { SetOption( optionName: LanguageServices.Implementation.SourceGeneratedFileManager.Options.EnableOpeningInWorkspace.Name, feature: LanguageServices.Implementation.SourceGeneratedFileManager.Options.EnableOpeningInWorkspace.Feature, value: value); } public void SetFeatureOption(string feature, string optionName, string language, string? valueString) => _inProc.SetFeatureOption(feature, optionName, language, valueString); public string? GetWorkingFolder() => _inProc.GetWorkingFolder(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .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; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.VisualStudio.IntegrationTest.Utilities.InProcess; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.OutOfProcess { public class VisualStudioWorkspace_OutOfProc : OutOfProcComponent { private readonly VisualStudioWorkspace_InProc _inProc; internal VisualStudioWorkspace_OutOfProc(VisualStudioInstance visualStudioInstance) : base(visualStudioInstance) { _inProc = CreateInProcComponent<VisualStudioWorkspace_InProc>(visualStudioInstance); } public void SetOptionInfer(string projectName, bool value) { _inProc.SetOptionInfer(projectName, value); WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace); } public void SetPersistenceOption(bool value) => SetOption("Enabled", PersistentStorageOptions.OptionName, value); public bool IsPrettyListingOn(string languageName) => _inProc.IsPrettyListingOn(languageName); public void SetPrettyListing(string languageName, bool value) => _inProc.SetPrettyListing(languageName, value); public void SetPerLanguageOption(string optionName, string feature, string language, object value) => _inProc.SetPerLanguageOption(optionName, feature, language, value); public void SetOption(string optionName, string feature, object value) => _inProc.SetOption(optionName, feature, value); public void WaitForAsyncOperations(TimeSpan timeout, string featuresToWaitFor, bool waitForWorkspaceFirst = true) => _inProc.WaitForAsyncOperations(timeout, featuresToWaitFor, waitForWorkspaceFirst); public void WaitForAllAsyncOperations(TimeSpan timeout, params string[] featureNames) => _inProc.WaitForAllAsyncOperations(timeout, featureNames); public void WaitForAllAsyncOperationsOrFail(TimeSpan timeout, params string[] featureNames) => _inProc.WaitForAllAsyncOperationsOrFail(timeout, featureNames); public void CleanUpWorkspace() => _inProc.CleanUpWorkspace(); public void ResetOptions() => _inProc.ResetOptions(); public void CleanUpWaitingService() => _inProc.CleanUpWaitingService(); public void SetQuickInfo(bool value) => _inProc.EnableQuickInfo(value); public void SetImportCompletionOption(bool value) { SetPerLanguageOption( optionName: "ShowItemsFromUnimportedNamespaces", feature: "CompletionOptions", language: LanguageNames.CSharp, value: value); SetPerLanguageOption( optionName: "ShowItemsFromUnimportedNamespaces", feature: "CompletionOptions", language: LanguageNames.VisualBasic, value: value); } public void SetArgumentCompletionSnippetsOption(bool value) { SetPerLanguageOption( optionName: CompletionOptions.EnableArgumentCompletionSnippets.Name, feature: CompletionOptions.EnableArgumentCompletionSnippets.Feature, language: LanguageNames.CSharp, value: value); SetPerLanguageOption( optionName: CompletionOptions.EnableArgumentCompletionSnippets.Name, feature: CompletionOptions.EnableArgumentCompletionSnippets.Feature, language: LanguageNames.VisualBasic, value: value); } public void SetTriggerCompletionInArgumentLists(bool value) { SetPerLanguageOption( optionName: CompletionOptions.TriggerInArgumentLists.Name, feature: CompletionOptions.TriggerInArgumentLists.Feature, language: LanguageNames.CSharp, value: value); } public void SetFullSolutionAnalysis(bool value) { SetPerLanguageOption( optionName: SolutionCrawlerOptions.BackgroundAnalysisScopeOption.Name, feature: SolutionCrawlerOptions.BackgroundAnalysisScopeOption.Feature, language: LanguageNames.CSharp, value: value ? BackgroundAnalysisScope.FullSolution : BackgroundAnalysisScope.Default); SetPerLanguageOption( optionName: SolutionCrawlerOptions.BackgroundAnalysisScopeOption.Name, feature: SolutionCrawlerOptions.BackgroundAnalysisScopeOption.Feature, language: LanguageNames.VisualBasic, value: value ? BackgroundAnalysisScope.FullSolution : BackgroundAnalysisScope.Default); } public void SetEnableOpeningSourceGeneratedFilesInWorkspaceExperiment(bool value) { SetOption( optionName: LanguageServices.Implementation.SourceGeneratedFileManager.Options.EnableOpeningInWorkspace.Name, feature: LanguageServices.Implementation.SourceGeneratedFileManager.Options.EnableOpeningInWorkspace.Feature, value: value); } public void SetFeatureOption(string feature, string optionName, string language, string? valueString) => _inProc.SetFeatureOption(feature, optionName, language, valueString); public string? GetWorkingFolder() => _inProc.GetWorkingFolder(); } }
-1